#示例2:按鈕 import tkinter as tk
class APP: def __init__(self, master): #root 傳參賦值給master frame = tk.Frame(master) #frame 組件 frame.pack(side=tk.LEFT, padx=10, pady=10)
self.hi_there = tk.Button(frame, text='打招呼', bg='black', fg='white', command=self.say_hi) #Button按鈕, command中調(diào)用定義的方法 self.hi_there.pack()
def say_hi(self): print('臥槽,居然打了個招呼!~')
root = tk.Tk() app = APP(root)
root.mainloop()
#示例3:圖片 from tkinter import *
root = Tk() textLabel = Label(root, text='請重試!\n您的操作不被允許!', #文字支持換行 justify=LEFT, #左對齊 padx=10, #左邊距10px pady=10) #右邊距10px textLabel.pack(side=LEFT)
#顯示圖片 photo = PhotoImage(file='tk_image.png') imageLabel = Label(root, image=photo) imageLabel.pack(side=RIGHT)
mainloop()
#示例4:背景 from tkinter import *
root = Tk()
photo = PhotoImage(file='tk4_bg.png') theLabel = Label(root, text='生存還是毀滅\n這是一個問題', justify=LEFT, image=photo, compound=CENTER, font=('華文隸書', 20), fg='blue') theLabel.pack()
mainloop()
#示例5:按鈕交互 from tkinter import *
def callback(): var.set('吹吧你,我才不信呢!')
root = Tk()
frame1 = Frame(root) frame2 = Frame(root)
var = StringVar() var.set('請重試!\n您的操作不被允許!') textLabel = Label(frame1, textvariable=var, justify=LEFT) #左對齊 textLabel.pack(side=LEFT)
#顯示圖片 photo = PhotoImage(file='tk_image.png') imageLabel = Label(root, image=photo) imageLabel.pack(side=RIGHT)
theButton = Button(frame2, text='我是超級管理員', command=callback) theButton.pack()
frame1.pack(padx=10, pady=10) frame2.pack(padx=10, pady=10)
mainloop()
#示例6:選項按鈕 from tkinter import *
root = Tk()
v = IntVar()
c = Checkbutton(root, text='測試一下', variable=v) #v用來存放選中狀態(tài) c.pack()
l = Label(root, textvariable=v) l.pack() #未選中顯示為0,選中顯示1
mainloop()
#示例7:多個方框選項 from tkinter import *
root = Tk()
GIRLS = ['西施', '貂蟬', '王昭君', '楊玉環(huán)']
v = [] for girl in GIRLS: v.append(IntVar()) b = Checkbutton(root, text=girl, variable=v[-1]) b.pack(anchor=W) #設(shè)置對齊方位,東E南S西W北N
mainloop()
#示例8:多個圓點選項 Radiobutton from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='one', variable=v, value=1).pack(anchor=W) Radiobutton(root, text='two', variable=v, value=2).pack(anchor=W) Radiobutton(root, text='three', variable=v, value=3).pack(anchor=W) Radiobutton(root, text='four', variable=v, value=4).pack(anchor=W)
mainloop()
#示例9:內(nèi)陷填充按鈕選項 Radiobutton indicatoron from tkinter import *
root = Tk()
LANGS = [ ('C', 1), ('C++', 2), ('shell', 3), ('python', 4)]
v = IntVar() v.set(1)
for lang, num in LANGS: #對應(yīng)列表中包含元組同時執(zhí)行多個循環(huán) b = Radiobutton(root, text=lang, variable=v, value=num, indicatoron=False) b.pack(fill=X)
mainloop()
#示例10:附帶標(biāo)題的圓點選項 LabelFrame from tkinter import *
root = Tk()
group = LabelFrame(root, text='最好的開發(fā)語言是?', padx=5, pady=5) group.pack(padx=10, pady=10)
LANGS = [ ('C', 1), ('C++', 2), ('shell', 3), ('python', 4)]
v = IntVar() v.set(1)
for lang, num in LANGS: #對應(yīng)列表中包含元組同時執(zhí)行多個循環(huán) b = Radiobutton(group, text=lang, variable=v, value=num) b.pack(anchor=W)
mainloop()
#示例11:輸入框 Entry from tkinter import *
root = Tk()
e = Entry(root) e.pack(padx=20, pady=20)
e.delete(0, END) e.insert(0, '默認文本...')
mainloop()
#示例12:按鈕和輸入框交互 from tkinter import *
root = Tk() root.title('輸入框與按鈕程序')
Label(root, text='作品:').grid(row=0, column=0) Label(root, text='作者:').grid(row=1, column=0)
e1 = Entry(root) e2 = Entry(root) e1.grid(row=0, column=1, padx=10, pady=5) e2.grid(row=1, column=1, padx=10, pady=5)
def show(): #當(dāng)輸入內(nèi)容時點擊獲取信息會打印 print('作品:《%s》' % e1.get()) print('作者:《%s》' % e2.get())
Button(root, text='獲取信息', width=10, command=show) \ .grid(row=3, column=0, sticky=W, padx=10, pady=5) Button(root, text='點擊退出', width=10, command=root.quit) \ .grid(row=3, column=1, sticky=E, padx=10, pady=5) #退出按鈕必須是雙擊打開.py文件才可以,而不是在IDLE下調(diào)試運行時
mainloop()
#示例12:登陸框程序 from tkinter import *
root = Tk() root.title('登陸程序')
Label(root, text='賬號:').grid(row=0, column=0) Label(root, text='密碼:').grid(row=1, column=0)
v1 = StringVar() v2 = StringVar()
e1 = Entry(root, textvariable=v1) e2 = Entry(root, textvariable=v2, show='*') e1.grid(row=0, column=1, padx=10, pady=5) e2.grid(row=1, column=1, padx=10, pady=5)
def show(): print('賬號:%s' % e1.get()) print('密碼:%s' % e2.get())
Button(root, text='芝麻開門', width=10, command=show) \ .grid(row=3, column=0, sticky=W, padx=10, pady=5) Button(root, text='點擊退出', width=10, command=root.quit) \ .grid(row=3, column=1, sticky=E, padx=10, pady=5) #退出按鈕必須是雙擊打開.py文件才可以,而不是在IDLE下調(diào)試運行時
mainloop()
#示例13:輸入對錯驗證程序 from tkinter import *
root = Tk() root.title('輸入對錯驗證')
def test(): if e1.get() == '張三': print('正確!') return True else: print('錯誤!') e1.delete(0, END) return False
v = StringVar()
#focusout指定在當(dāng)前輸入框失去焦點時,代表輸入完,會去調(diào)用test校驗<tab>鍵可測試 e1 = Entry(root, textvariable=v, validate='focusout', validatecommand=test) e2 = Entry(root) e1.pack(padx=10, pady=10) e2.pack(padx=10, pady=10)
mainloop() (第一欄不是張三,則會清空第一欄內(nèi)容)
#示例13:簡單計算器程序 from tkinter import *
root = Tk() root.title('計算器程序')
frame = Frame(root) frame.pack(padx=10, pady=10)
v1 = StringVar() v2 = StringVar() v3 = StringVar()
def test(content): return content.isdigit()
testCMD = frame.register(test) #focusout指定在當(dāng)前輸入框失去焦點時,代表輸入完,會去調(diào)用test校驗<tab>鍵可測試 e1 = Entry(frame, width=10, textvariable=v1, validate='key', \ validatecommand=(testCMD, '%P')).grid(row=0, column=0) #width的單位是字符數(shù) Label(frame, text='+').grid(row=0, column=1)
e2 = Entry(frame, width=10, textvariable=v2, validate='key', \ validatecommand=(testCMD, '%P')).grid(row=0, column=2) Label(frame, text='=').grid(row=0, column=3)
e3 = Entry(frame, width=10, textvariable=v3, state='readonly').grid(row=0, column=4)
def calc(): result = int(v1.get()) + int(v2.get()) v3.set(str(result))
Button(frame, text='計算結(jié)果', command=calc).grid(row=1, column=2, pady=5)
mainloop()
#示例14:按鈕刪除列表中的選項 from tkinter import *
master= Tk()
theLB = Listbox(master, selectmode=SINGLE, height=15) #SINGLE單選,MULTIPLE多選,height設(shè)置顯示項數(shù) theLB.pack()
for item in ['筆', '墨', '紙', '硯']: theLB.insert(END, item) #END表示最后一個
for item in range(11): theLB.insert(END, item)
theButton = Button(master, text='刪除', \ command=lambda x=theLB:x.delete(ACTIVE) ) #ACTIVE表示當(dāng)前選中的值 theButton.pack()
mainloop() [刪除]
#示例15:為列表組件添加滾動條 #安裝垂直滾動條步驟: #1) 設(shè)置該組件的yscrollbarcommand選項為Scrollbar組件的set方法; #2) 設(shè)置Scrollbar組件的command選項為該組件的yview()方法。 from tkinter import *
root = Tk() root.title('滾動條程序')
sb = Scrollbar(root) sb.pack(side=RIGHT, fill=Y)
lb = Listbox(root, yscrollcommand=sb.set)
for i in range(1000): lb.insert(END, i) lb.pack(side=LEFT, fill=BOTH)
#讓滾動條與選項互通互連 sb.config(command=lb.yview)
mainloop()
#示例16:滑塊滾動條 Scale from tkinter import *
root = Tk() root.title('滑塊程序')
s1 = Scale(root, from_=0, to=100, tickinterval=5, resolution=5, length=200) #默認是垂直, tickinterval精度刻度, length單位是像素 s1.pack()
s2 = Scale(root, from_=0, to=100, tickinterval=5, orient=HORIZONTAL, length=400) s2.pack()
def show(): print(s1.get(), s2.get())
#獲取滑塊的當(dāng)前位置,點擊后才有效 Button(root, text='音量:', command=show).pack()
mainloop()
#示例17:文本組件 Text (插入按鈕) from tkinter import *
root = Tk() root.title('Text')
text = Text(root, width=30, height=20) text.pack()
#窗口中的文本可編輯 text.insert(INSERT, '這里是顯示的文本信息內(nèi)容。\n') #INSERT表示輸入光標(biāo)插入的位置 text.insert(END, '對比一下效果。')
def show(): print('提交中...') #此行內(nèi)容顯示在IDLE中
#插入一個Button組件 b1 = Button(text, text='提交', command=show) text.window_create(INSERT, window=b1) #將b1插入
mainloop()
#示例18:文本組件 Text (插入圖片) from tkinter import *
root = Tk() root.title('Text')
text = Text(root, width=50, height=15) text.pack()
photo = PhotoImage(file="tk_image.png") def show_img(): text.image_create(END, image=photo)
#插入一個圖片 b1 = Button(text, text='插入圖片', command=show_img) text.window_create(INSERT, window=b1) #將b1插入
mainloop()
#示例19:文本組件 Text (Indexes:索引定位) from tkinter import *
root = Tk() root.title('Text')
text = Text(root, width=30, height=10) text.pack() text.insert(INSERT, 'I love baidu.com!')
text.tag_add('tag1', '1.7', '1.12', '1.14') #1.7~1.12 baidu 1.14 o text.tag_add('tag2', '1.7', '1.12', '1.14') text.tag_config('tag1', background='blue', foreground='yellow') text.tag_config('tag2', foreground='red') #文字會以red為準(zhǔn)
mainloop()
#示例20:文本組件中可點擊連接 from tkinter import * import webbrowser as wb
root = Tk() root.title('GUI link show')
text = Text(root, width=30, height=5) text.pack()
text.insert(INSERT, 'I love baidu.com!') text.tag_add('link', '1.7', '1.16') text.tag_config('link', foreground='blue', underline=True)
def show_arrow_cursor(event): text.config(cursor='arrow')
def show_xterm_cursor(event): text.config(cursor='xterm')
def click(event): wb.open('http://www.baidu.com')
#綁定事件 text.tag_bind('link', '<Enter>', show_arrow_cursor) #<Enter>鼠標(biāo)進入 text.tag_bind('link', '<Leave>', show_xterm_cursor) #<Enter>鼠標(biāo)離開 text.tag_bind('link', '<Button-1>', click) #<Enter>鼠標(biāo)點擊
mainloop() (鏈接可點擊)
#示例21:文本組件之MD5 from tkinter import * import hashlib #用于獲取文件的MD5值,檢查內(nèi)容是否有修改
root = Tk() root.title('link click')
text = Text(root, width=50, height=10) text.pack()
text.insert(INSERT, 'I love www.baidu.com') contents = text.get('1.0', END)
def getSig(contents): m = hashlib.md5(contents.encode()) return m.digest()
sig = getSig(contents)
def check(): contents = text.get('1.0', END) if sig != getSig(contents): print('內(nèi)容有修改,是否保存?') else: print('無任何修改!')
Button(root, text='檢查', command=check).pack()
mainloop()
#示例22:文本組件之全文搜索 from tkinter import *
root = Tk() root.title('link click')
text = Text(root, width=50, height=10) text.pack()
text.insert(INSERT, 'I love www.baidu.com')
def getIndex(text, index): return tuple(map(int, str.split(text.index(index), '.')))
start = '1.0' #開頭的位置,第1行的第0個下標(biāo)位置 while True: pos = text.search('o', start, stopindex=END) #查找文本中字符o的位置 if not pos: break print('找到啦,位置是:', getIndex(text, pos)) start = pos + '+1c' #'+1c'指向下一個字符
mainloop()
#示例23:文本組件之撤銷操作 from tkinter import *
root = Tk() root.title('link click')
text = Text(root, width=50, height=10, undo=True) #undo模式開啟 text.pack()
text.insert(INSERT, 'I love www.baidu.com')
def show(): text.edit_undo()
Button(root, text='撤銷', command=show).pack() #多次撤銷會刪除文本組件內(nèi)的內(nèi)容
mainloop()
#示例24:繪制組件 Canvas from tkinter import *
root = Tk() root.title('Canvas')
w = Canvas(root, width=500, height=300) #background='black' 改變背景色 w.pack()
#黃色的矩形 w.create_rectangle(50, 50, 450, 250, fill='yellow') #參數(shù):左邊距, 上邊距, 寬, 高 #紅色的橫線 w.create_line(0, 300//2, 500, 300//2, fill='red') #藍色的豎虛線 w.create_line(500//2, 0, 500//2, 300, fill='blue', dash=(4, 4)) #dash 虛線
mainloop()
#示例25:繪制組件 Canvas (修改和刪除圖形) from tkinter import *
root = Tk() root.title('Canvas')
w = Canvas(root, width=500, height=300) #background='black' 改變背景色 w.pack()
rect1 = w.create_rectangle(50, 50, 450, 250, fill='yellow') #參數(shù):左邊距, 上邊距, 寬, 高 line1 = w.create_line(0, 300//2, 500, 300//2, fill='red') line2 = w.create_line(500//2, 0, 500//2, 300, fill='blue', dash=(4, 4)) #dash 虛線
w.coords(line1, 0, 25, 500, 25) #移動位置 w.itemconfig(rect1, fill='red') w.delete(line2)
Button(root, text='刪除全部', command=(lambda x=ALL:w.delete(x))).pack()
mainloop()
#示例26:繪制組件 Canvas (圖形正中心) from tkinter import *
root = Tk() root.title('Canvas')
w = Canvas(root, width=600, height=300) w.pack()
line1 = w.create_line(0, 0, 600, 300, fill='green', width=3) line1 = w.create_line(600, 0, 0, 300, fill='green', width=3) rect1 = w.create_rectangle(60, 30, 540, 270, fill='green') rect2 = w.create_rectangle(120, 60, 480, 240, fill='yellow')
w.create_text(300, 150, text='Hello, python!')
mainloop()
#示例27:繪制組件 Canvas (橢圓和圓形) from tkinter import *
root = Tk() root.title('Canvas')
w = Canvas(root, width=600, height=300) w.pack()
w.create_rectangle(60, 30, 540, 270, dash=(4, 4)) w.create_oval(60, 30, 540, 270, fill='pink') #橢圓是通過限定矩形的方式畫出來,圓形通過正方形 #w.create_oval(60, 30, 300, 270, fill='pink') #正方形對應(yīng)正圓(60-300=30-270) w.create_text(300, 150, text='wow~')
mainloop()
#示例28:繪制組件 Canvas (五角星) from tkinter import * import math as m #用到sin和cos數(shù)學(xué)函數(shù)
root = Tk() root.title('Canvas')
w = Canvas(root, width=600, height=300, background='red') w.pack()
center_x = 300 center_y = 150 r = 150
points = [ #左上點 center_x - int(r * m.sin(2 * m.pi / 5)), center_y - int(r * m.cos(2 * m.pi / 5)), #右上點 center_x + int(r * m.sin(2 * m.pi / 5)), center_y - int(r * m.cos(2 * m.pi / 5)), #左下點 center_x - int(r * m.sin(m.pi / 5)), center_y + int(r * m.cos(m.pi / 5)), #頂點 center_x, center_y - r, #右下點 center_x + int(r * m.sin(m.pi / 5)), center_y + int(r * m.cos(m.pi / 5)), ]
w.create_polygon(points, outline='yellow', fill='yellow') #polygon多邊形
mainloop()
#示例29:繪制組件 Canvas (自定義畫板) #繪制一個極小的圓來代表一個點(tkinter本身不支持畫點) from tkinter import *
root = Tk() root.title('Canvas draw tool')
w = Canvas(root, width=400, height=200, background='white') w.pack()
def paint(event): x1, y1 = (event.x - 1), (event.y - 1) x2, y2 = (event.x + 1), (event.y + 1) w.create_oval(x1, y1, x2, y2, fill='red')
w.bind('<B1-Motion>', paint) #<B1-Motion>綁定鼠標(biāo)左鍵事件
Label(root, text='按住鼠標(biāo)左鍵并移動,開始繪制吧!~~').pack(side=BOTTOM)
mainloop()
#示例30:菜單組件框架 Menu (主菜單/下拉菜單/右鍵菜單/單多選菜單/按鈕菜單/選項菜單(列表)) from tkinter import *
root = Tk() root.title('Main Menu Show')
def callback(): print('你好~')
menubar = Menu(root)
#注冊菜單:文件(下拉菜單) filemenu = Menu(menubar, tearoff=False) #來自主菜單,tearoff參數(shù)可讓菜單窗口分離 filemenu.add_command(label='新建', command=callback) filemenu.add_command(label='打開...', command=callback) filemenu.add_separator() #分割線 filemenu.add_command(label='保存', command=callback) filemenu.add_separator() #分割線 filemenu.add_command(label='退出', command=root.quit) menubar.add_cascade(label='文件(W)', menu=filemenu)
#主菜單:編輯(下拉菜單) editmenu = Menu(menubar, tearoff=False) #來自主菜單 editmenu.add_command(label='撤銷', command=callback) editmenu.add_command(label='重做', command=callback) editmenu.add_separator() #分割線 editmenu.add_command(label='剪切', command=callback) editmenu.add_command(label='復(fù)制', command=callback) editmenu.add_command(label='粘貼', command=callback) editmenu.add_separator() #分割線 editmenu.add_command(label='全選', command=callback) editmenu.add_separator() #分割線 editmenu.add_command(label='查找...', command=callback) menubar.add_cascade(label='編輯(B)', menu=editmenu)
#主菜單:多選√ checkbutton(下拉菜單) openVar = IntVar() saveVar = IntVar() quitVar = IntVar() optionmenu = Menu(menubar, tearoff=False) optionmenu.add_checkbutton(label='多選項1', command=callback, variable=openVar) optionmenu.add_checkbutton(label='多選項2', command=callback, variable=saveVar) optionmenu.add_checkbutton(label='多選項3', command=callback, variable=quitVar) menubar.add_cascade(label='選項(C)', menu=optionmenu)
#主菜單:單選√ radiobutton(下拉菜單) otherVar = IntVar() othermenu = Menu(menubar, tearoff=False) othermenu.add_radiobutton(label='單選項1', command=callback, variable=otherVar, value=1) othermenu.add_radiobutton(label='單選項2', command=callback, variable=otherVar, value=2) othermenu.add_radiobutton(label='單選項3', command=callback, variable=otherVar, value=3) menubar.add_cascade(label='其他(C)', menu=othermenu)
#內(nèi)部菜單:按鈕菜單 Menubutton mb = Menubutton(root, text='按鈕菜單...', relief=RAISED) mb.pack() openVar = IntVar() saveVar = IntVar() quitVar = IntVar() optionmenu = Menu(mb, tearoff=False) optionmenu.add_checkbutton(label='test', command=callback, variable=openVar) optionmenu.add_checkbutton(label='test', command=callback, variable=saveVar) optionmenu.add_checkbutton(label='test', command=callback, variable=quitVar) mb.config(menu=optionmenu)
#內(nèi)部菜單:選項菜單 OptionMenu variable = StringVar() variable.set('one') #默認顯示one w = OptionMenu(root, variable, 'one', 'two', 'three') w.pack()
#將列表添加到選項菜單 OptionMenu OPTIONS = [ '表項1', '對比2', '選項3', '其他4', '退出5' ] var = StringVar() var.set(OPTIONS[0]) o = OptionMenu(root, var, *OPTIONS) #*星號解包可變參數(shù)列表為逐個元素 o.pack()
#主菜單:幫助 helpmenu = Menu(menubar, tearoff=False) helpmenu.add_separator() #分割線 helpmenu.add_command(label='關(guān)于...', command=callback) helpmenu.add_separator() #分割線 menubar.add_cascade(label='幫助(F1)', menu=helpmenu)
#彈出菜單(暫用編輯菜單作為右鍵) frame = Frame(root, width=500, height=200) frame.pack() def popup(event): editmenu.post(event.x_root, event.y_root) frame.bind('<Button-3>', popup) #Button-3為鼠標(biāo)右鍵,1為左鍵,2為中鍵
root.config(menu=menubar) #menu參數(shù)會將菜單設(shè)置添加到root根窗口
mainloop()
#示例31:事件綁定 bind (鼠標(biāo)/按鍵/按鍵組合) from tkinter import *
root = Tk() root.title('Event bind')
frame = Frame(root, width=200, height=200) #鼠標(biāo)響應(yīng)事件 def callback1(event): #event形參獲取事件描述,必備參數(shù) print('點擊位置:', event.x, event.y) frame.bind('<Button-1>', callback1) #Button表示鼠標(biāo)點擊事件, 12345分別代表左中右鍵上滾下滾 frame.pack()
#鍵盤響應(yīng)事件 def callback2(event): print(event.keysym) #打印信息在IDLE, keysym指鍵盤所有按鍵 frame.bind('<Key>', callback2) frame.focus_set() frame.pack()
#鼠標(biāo)即時響應(yīng)事件 def callback3(event): print('點擊位置:', event.x, event.y) frame.bind('<Motion>', callback3) #鼠標(biāo)在窗口內(nèi)只要有移動就一直輸出位置 frame.pack()
#事件序列(按鍵組合),語法:<modifier-type-detail> 如 #點擊鼠標(biāo)左鍵:<Button-1> ButtonRelease更安全,移除組件釋放點擊時不去觸發(fā) #點擊H字母按鍵:<KeyPress-H> #同時點擊Ctrl+Shift+H:<Control-Shift-KeyPress-H> mainloop()
#示例32:消息組件 Message | 輸入組件 Spinbox from tkinter import *
root = Tk() root.title('Module')
#消息組件:Message m1 = Message(root, text='這是一個消息:', width=100) m1.pack()
m2 = Message(root, text='這是一\n則駭人聽聞的長長長長長長長消息!', width=100) m2.pack()
#輸入組件:Spinbox (可指定輸入范圍) s1 = Spinbox(root, from_=0, to=5) s1.pack() s2 = Spinbox(root, values=('zero', 'one', 'two', 'three', 'four', 'five')) s2.pack()
mainloop()
#示例33:窗口布局管理器 PanedWindow from tkinter import *
root = Tk() root.title('Module')
#二窗格 ''' p = PanedWindow(orient=VERTICAL) p.pack(fill=BOTH, expand=1)
top = Label(p, text='top pane') p.add(top)
bottom = Label(p, text='bottom pane') p.add(bottom) ''' #三窗格,同時顯示隱藏布局線(showhandle=True, sashrelief=SUNKEN) p = PanedWindow(showhandle=True, sashrelief=SUNKEN) p.pack(fill=BOTH, expand=1)
left = Label(p, text='left pane') p.add(left)
q = PanedWindow(orient=VERTICAL, showhandle=True, sashrelief=SUNKEN) p.add(q)
top = Label(q, text='top pane') q.add(top) bottom = Label(q, text='bottom pane') q.add(bottom)
mainloop()
#示例34:容器組件 Toplevel (創(chuàng)建頂級窗口,即彈出窗口) from tkinter import *
root = Tk() root.title('Toplevel')
def create(): top = Toplevel() #top.attributes('-alpha', 0.5) 設(shè)置彈出的頂級窗口透明度:50% top.title('Toplevel demo...')
msg = Message(top, text='I love python...') msg.pack()
Button(root, text='創(chuàng)建頂級窗口', command=create).pack() #點擊出現(xiàn)頂級窗口
mainloop()
#示例35:幾何管理類,包pack(),網(wǎng)格grid(),位置place() #pack() 注意pack和grid不要混合使用 from tkinter import *
root = Tk() root.title('pack')
#Listbox完全填充測試 listbox = Listbox(root) listbox.pack(fill=BOTH, expand=True) #fill=BOTH將窗口填滿 for i in range(10): listbox.insert(END, str(i))
#Label縱向填充 Label(root, text='red', bg='red', fg='white').pack(fill=X) Label(root, text='green', bg='green', fg='black').pack(fill=X) Label(root, text='blue', bg='blue', fg='white').pack(fill=X)
#Label橫向填充 Label(root, text='red', bg='red', fg='white').pack(side=LEFT) Label(root, text='green', bg='green', fg='black').pack(side=LEFT) Label(root, text='blue', bg='blue', fg='white').pack(side=LEFT)
mainloop()
#示例35:幾何管理類,包pack(),網(wǎng)格grid(),位置place() #grid() 注意pack和grid不要混合使用 from tkinter import *
root = Tk() root.title('grid')
#兩個sticky=W實現(xiàn)第一列左對齊 Label(root, text='用戶名').grid(row=0, sticky=W) Label(root, text='密碼').grid(row=1, sticky=W)
#rowspan=2可以讓圖片橫跨2行 photo = PhotoImage(file='tk_image.png') Label(root, image=photo).grid(row=0, column=2, rowspan=2, padx=5, pady=5)
Entry(root).grid(row=0, column=1) Entry(root, show='*').grid(row=1, column=1)
def callback(): print('登陸中...')
#columnspan=3可以讓按鈕橫跨3列 Button(text='提交', width=10, command=callback).grid(row=2, columnspan=3, pady=5)
mainloop()
#示例35:幾何管理類,包pack(),網(wǎng)格grid(),位置place() #place() 可以實現(xiàn)一些pack和grid實現(xiàn)不了的布局 from tkinter import *
root = Tk() root.title('place')
#place位置布局測試 ''' photo = PhotoImage(file='tk_image.png') Label(root, image=photo).pack() #按鈕就會出現(xiàn)在圖片的組件上,實現(xiàn)組件疊加顯示
def callback(): print('正中靶心?。?!')
#relx,rely相對父組件root的位置,0.5正中間,1最右邊,0最左邊,anchor=CENTER居中顯示 Button(root, text='射擊', command=callback).place(relx=0.5, rely=0.5, anchor=CENTER) ''' Label(root, bg='red').place(relx=0.5, rely=0.5, relheight=0.75, relwidth=0.75, anchor=CENTER) Label(root, bg='yellow').place(relx=0.5, rely=0.5, relheight=0.5, relwidth=0.5, anchor=CENTER) Label(root, bg='blue').place(relx=0.5, rely=0.5, relheight=0.25, relwidth=0.25, anchor=CENTER)
mainloop()
#示例35:對話框 (警告 showinfo | 消息 messagebox | 文件 filedialog | 顏色 colorchooser) from tkinter import * from tkinter import messagebox #messagebox()需要單獨導(dǎo)入 from tkinter import filedialog #filedialog()需要單獨導(dǎo)入 from tkinter import colorchooser #colorchooser()需要單獨導(dǎo)入 from tkinter.messagebox import * #用戶使用showinfo()
#警告對話框 showinfo(title='test', message='警告')
#消息對話框 result = messagebox.askokcancel('demo', '發(fā)射核彈?') #返回值是True或False print(result) #根據(jù)用戶按下了確定還是取消做進一步的操作
#文件對話框 root = Tk() def callback1(): filename = filedialog.askopenfilename(defaultextension='.py') #指定文件后綴 print(filename) #返回的是文件的完整路徑
Button(root, text='打開文件', command=callback1).pack()
#顏色選擇對話框 def callback2(): color_data = colorchooser.askcolor() #調(diào)用windows的顏色選擇器 print(color_data) #選擇紅色打?。?(255.99609375, 0.0, 0.0), '#ff0000')
Button(root, text='選擇顏色', command=callback2).pack()
mainloop()
|
|