來源:https://www.cnblogs.com/aland-1415/p/6849193.html
1矾削、使用tkinter.Tk() 生成主窗口(root=tkinter.Tk())
root.title('標(biāo)題名') 修改框體的名字,也可在創(chuàng)建時使用className參數(shù)來命名;
root.resizable(0,0) 框體大小可調(diào)性,分別表示x,y方向的可變性;
root.geometry('250x150') 指定主框體大小雾家;
root.quit() 退出;
root.update_idletasks()
root.update() 刷新頁面;
2趁耗、初級樣例
1 import tkinter 2 root=tkinter.Tk() #生成root主窗口
3 label=tkinter.Label(root,text='Hello,GUI') #生成標(biāo)簽
4 label.pack() #將標(biāo)簽添加到主窗口
5 button1=tkinter.Button(root,text='Button1') #生成button1
6 button1.pack(side=tkinter.LEFT) #將button1添加到root主窗口
7 button2=tkinter.Button(root,text='Button2') 8 button2.pack(side=tkinter.RIGHT) 9 root.mainloop() #進(jìn)入消息循環(huán)(必需組件)
3、tkinter中的15種核心組件
Button 按鈕疆虚;
Canvas 繪圖形組件苛败,可以在其中繪制圖形;
Checkbutton 復(fù)選框径簿;
Entry 文本框(單行)罢屈;
Text 文本框(多行);
Frame 框架篇亭,將幾個組件組成一組
Label 標(biāo)簽缠捌,可以顯示文字或圖片;
Listbox 列表框译蒂;
Menu 菜單曼月;
Menubutton 它的功能完全可以使用Menu替代肃叶;
Message 與Label組件類似,但是可以根據(jù)自身大小將文本換行十嘿;
Radiobutton 單選框因惭;
Scale 滑塊;允許通過滑塊來設(shè)置一數(shù)字值
Scrollbar 滾動條绩衷;配合使用canvas, entry, listbox, and text窗口部件的標(biāo)準(zhǔn)滾動條蹦魔;
Toplevel 用來創(chuàng)建子窗口窗口組件。
(在Tkinter中窗口部件類沒有分級咳燕;所有的窗口部件類在樹中都是兄弟勿决。)
4、組件的放置和排版(pack,grid,place)
pack組件設(shè)置位置屬性參數(shù):
after: 將組件置于其他組件之后招盲;
before: 將組件置于其他組件之前低缩;
anchor: 組件的對齊方式,頂對齊'n',底對齊's',左'w',右'e' side: 組件在主窗口的位置曹货,可以為'top','bottom','left','right'(使用時tkinter.TOP,tkinter.E)咆繁;
fill 填充方式 (Y,垂直,X顶籽,水平)
expand 1可擴(kuò)展玩般,0不可擴(kuò)展
grid組件使用行列的方法放置組件的位置,參數(shù)有:
column: 組件所在的列起始位置礼饱;
columnspam: 組件的列寬坏为;
row: 組件所在的行起始位置;
rowspam: 組件的行寬镊绪;
place組件可以直接使用坐標(biāo)來放置組件匀伏,參數(shù)有:
anchor: 組件對齊方式;
x: 組件左上角的x坐標(biāo)蝴韭;
y: 組件右上角的y坐標(biāo)够颠;
relx: 組件相對于窗口的x坐標(biāo),應(yīng)為0-1之間的小數(shù)万皿;
rely: 組件相對于窗口的y坐標(biāo)摧找,應(yīng)為0-1之間的小數(shù)核行;
width: 組件的寬度牢硅;
heitht: 組件的高度;
relwidth: 組件相對于窗口的寬度芝雪,0-1减余;
relheight: 組件相對于窗口的高度,0-1惩系;
** 5位岔、使用tkinter.Button時控制按鈕的參數(shù)**
anchor: 指定按鈕上文本的位置如筛;
background(bg) 指定按鈕的背景色;
bitmap: 指定按鈕上顯示的位圖抒抬;
borderwidth(bd) 指定按鈕邊框的寬度杨刨;
command: 指定按鈕消息的回調(diào)函數(shù);
cursor: 指定鼠標(biāo)移動到按鈕上的指針樣式擦剑;
font: 指定按鈕上文本的字體妖胀;
foreground(fg) 指定按鈕的前景色;
height: 指定按鈕的高度惠勒;
image: 指定按鈕上顯示的圖片赚抡;
state: 指定按鈕的狀態(tài)(disabled);
text: 指定按鈕上顯示的文本纠屋;
width: 指定按鈕的寬度
padx 設(shè)置文本與按鈕邊框x的距離涂臣,還有pady;
activeforeground 按下時前景色
textvariable 可變文本,與StringVar等配合著用
6售担、文本框tkinter.Entry,tkinter.Text控制參數(shù)
background(bg) 文本框背景色赁遗;
foreground(fg) 前景色;
selectbackground 選定文本背景色族铆;
selectforeground 選定文本前景色吼和;
borderwidth(bd) 文本框邊框?qū)挾龋?br>
font 字體;
show 文本框顯示的字符骑素,若為*炫乓,表示文本框?yàn)槊艽a框;
state 狀態(tài)献丑;
width 文本框?qū)挾?br>
textvariable 可變文本末捣,與StringVar等配合著用
7、標(biāo)簽tkinter.Label組件控制參數(shù)
Anchor 標(biāo)簽中文本的位置创橄;
background(bg) 背景色箩做;
foreground(fg) 前景色;
borderwidth(bd) 邊框?qū)挾龋?br>
width 標(biāo)簽寬度妥畏;
height 標(biāo)簽高度邦邦;
bitmap 標(biāo)簽中的位圖;
font 字體醉蚁;
image 標(biāo)簽中的圖片燃辖;
justify 多行文本的對齊方式;
text 標(biāo)簽中的文本网棍,可以使用'\n'表示換行
textvariable 顯示文本自動更新黔龟,與StringVar等配合著用
****8、單選框和復(fù)選框Radiobutton,Checkbutton控制參數(shù)****
anchor 文本位置;
background(bg) 背景色氏身;
foreground(fg) 前景色巍棱;
borderwidth 邊框?qū)挾龋?br>
width 組件的寬度;
height 組件高度蛋欣;
bitmap 組件中的位圖航徙;
image 組件中的圖片;
font 字體陷虎;
justify 組件中多行文本的對齊方式捉偏;
text 指定組件的文本;
value 指定組件被選中中關(guān)聯(lián)變量的值泻红;
variable 指定組件所關(guān)聯(lián)的變量夭禽;
indicatoron 特殊控制參數(shù),當(dāng)為0時谊路,組件會被繪制成按鈕形式;
textvariable 可變文本顯示讹躯,與StringVar等配合著用
9、組圖組件Canvas控制參數(shù)
background(bg) 背景色;
foreground(fg) 前景色;
borderwidth 組件邊框?qū)挾龋?br>
width 組件寬度缠劝;
height 高度;
bitmap 位圖;
image 圖片;
繪圖的方法主要以下幾種:
create_arc 圓弧;
create_bitmap 繪制位圖潮梯,支持XBM;
create_image 繪制圖片,支持GIF(x,y,image,anchor);
create_line 繪制支線惨恭;
create_oval; 繪制橢圓秉馏;
create_polygon 繪制多邊形(坐標(biāo)依次羅列,不用加括號脱羡,還有參數(shù)萝究,fill,outline);
create_rectangle 繪制矩形((a,b,c,d),值為左上角和右下角的坐標(biāo))锉罐;
create_text 繪制文字(字體參數(shù)font,)帆竹;
create_window 繪制窗口;
delete 刪除繪制的圖形脓规;
itemconfig 修改圖形屬性栽连,第一個參數(shù)為圖形的ID,后邊為想修改的參數(shù)侨舆;
move 移動圖像(1秒紧,4,0)挨下,1為圖像對象熔恢,4為橫移4像素,0為縱移像素复颈,然后用root.update()刷新即可看到圖像的移動绩聘,為了使多次移動變得可視,最好加上time.sleep()函數(shù)耗啦;
只要用create_方法畫了一個圖形凿菩,就會自動返回一個ID,創(chuàng)建一個圖形時將它賦值給一個變量,需要ID時就可以使用這個變量名帜讲。
coords(ID) 返回對象的位置的兩個坐標(biāo)(4個數(shù)字元組)衅谷;
對于按鈕組件、菜單組件等可以在創(chuàng)建組件時通過command參數(shù)指定其事件處理函數(shù)似将。方法為bind;或者用bind_class方法進(jìn)行類綁定获黔,bind_all方法將所有組件事件綁定到事件響應(yīng)函數(shù)上。</pre>
** **10在验、菜單Menu****
參數(shù):
tearoff 分窗玷氏,0為在原窗,1為點(diǎn)擊分為兩個窗口
bg,fg 背景腋舌,前景
borderwidth 邊框?qū)挾?br>
font 字體
activebackgound 點(diǎn)擊時背景盏触,同樣有activeforeground,activeborderwidth块饺,disabledforeground
cursor
postcommand
selectcolor 選中時背景
takefocus
title
type
relief
方法:
menu.add_cascade 添加子選項(xiàng)
menu.add_command 添加命令(label參數(shù)為顯示內(nèi)容)
menu.add_separator 添加分隔線
menu.add_checkbutton 添加確認(rèn)按鈕
delete 刪除</pre>
11赞辩、事件關(guān)聯(lián)
bind(sequence,func,add)——
bind_class(className,sequence,func,add)
bind_all(sequence,func,add)
事件參數(shù):
sequence 所綁定的事件;
func 所綁定的事件處理函數(shù)授艰;
add 可選參數(shù)辨嗽,為空字符或‘+’;
className 所綁定的類淮腾;
鼠標(biāo)鍵盤事件 <Button-1> 鼠標(biāo)左鍵按下糟需,2表示中鍵,3表示右鍵谷朝; <ButtonPress-1> 同上篮灼; <ButtonRelease-1>鼠標(biāo)左鍵釋放; <B1-Motion> 按住鼠標(biāo)左鍵移動徘禁; <Double-Button-1> 雙擊左鍵诅诱; <Enter> 鼠標(biāo)指針進(jìn)入某一組件區(qū)域; <Leave> 鼠標(biāo)指針離開某一組件區(qū)域送朱; <MouseWheel> 滾動滾輪娘荡; <KeyPress-A> 按下A鍵,A可用其他鍵替代驶沼; <Alt-KeyPress-A>同時按下alt和A炮沐;alt可用ctrl和shift替代; <Double-KeyPress-A> 快速按兩下A回怜; <Lock-KeyPress-A> 大寫狀態(tài)下按A大年;
窗口事件
Activate 當(dāng)組件由不可用轉(zhuǎn)為可用時觸發(fā);
Configure 當(dāng)組件大小改變時觸發(fā);
Deactivate 當(dāng)組件由可用轉(zhuǎn)變?yōu)椴豢捎脮r觸發(fā)翔试;
Destroy 當(dāng)組件被銷毀時觸發(fā)轻要;
Expose 當(dāng)組件從被遮擋狀態(tài)中暴露出來時觸發(fā);
Unmap 當(dāng)組件由顯示狀態(tài)變?yōu)殡[藏狀態(tài)時觸發(fā)垦缅;
Map 當(dāng)組件由隱藏狀態(tài)變?yōu)轱@示狀態(tài)時觸發(fā)冲泥;
FocusIn 當(dāng)組件獲得焦點(diǎn)時觸發(fā);
FocusOut 當(dāng)組件失去焦點(diǎn)時觸發(fā)壁涎;
Property 當(dāng)窗體的屬性被刪除或改變時觸發(fā)凡恍;
Visibility 當(dāng)組件變?yōu)榭梢暊顟B(tài)時觸發(fā);
響應(yīng)事件
event對象(def function(event)):
char 按鍵字符怔球,僅對鍵盤事件有效嚼酝;
keycode 按鍵名,僅對鍵盤事件有效竟坛;
keysym 按鍵編碼革半,僅對鍵盤事件有效;
num 鼠標(biāo)按鍵流码,僅對鼠標(biāo)事件有效又官;
type 所觸發(fā)的事件類型;
widget 引起事件的組件漫试;
width,heigh 組件改變后的大小六敬,僅Configure有效;
x,y 鼠標(biāo)當(dāng)前位置驾荣,相對于窗口外构;
x_root,y_root 鼠標(biāo)當(dāng)前位置,相對于整個屏幕</pre>
12播掷、彈窗
messagebox._show函數(shù)的控制參數(shù):
default 指定消息框按鈕审编;
icon 指定消息框圖標(biāo);
message 指定消息框所顯示的消息歧匈;
parent 指定消息框的父組件垒酬;
title 標(biāo)題;
type 類型件炉;
simpledialog模塊參數(shù):
title 指定對話框的標(biāo)題勘究;
prompt 顯示的文字;
initialvalue 指定輸入框的初始值斟冕;
filedialog 模塊參數(shù):
filetype 指定文件類型口糕;
initialdir 指定默認(rèn)目錄;
initialfile 指定默認(rèn)文件磕蛇;
title 指定對話框標(biāo)題
colorchooser模塊參數(shù):
initialcolor 指定初始化顏色景描;
title 指定對話框標(biāo)題十办;</pre>
13、字體(font)
一般格式:
('Times -10 bold')
('Times',10,'bold','italic') 依次表示字體超棺、字號向族、加粗、傾斜
補(bǔ)充:
config 重新配置
label.config(font='Arial -%d bold' % scale.get())
依次為字體说搅,大姓ㄔ妗(大小可為字號大新驳取)弄唧,加粗
tkinter.StringVar 能自動刷新的字符串變量,可用set和get方法進(jìn)行傳值和取值霍衫,類似的還有IntVar,DoubleVar...
sys.stdout.flush() 刷新輸出
附1:tkinter中的顏色
附2:一個自己用tkinter寫的計算器程序
1 #filename:Caculater
2
3 import tkinter,time,decimal,math,string 4
5 root=tkinter.Tk()
6 root.title('計算器')
7 root.resizable(0,0)
8 global cuncu, vartext, result, fuhao 9 result = fuhao = None 10 vartext = tkinter.StringVar() 11 cuncu = [] 12
13 class anjianzhi: 14 global cuncu, vartext, result, fuhao 15 def init(self,anjian):
16 self.anjian = anjian 17 def jia(self): 18 cuncu.append(self.anjian)
19 vartext.set( ''.join(cuncu))
20 def tui(self): 21 cuncu.pop()
22 vartext.set(''.join(cuncu))
23 def clear(self): 24 cuncu.clear()
25 vartext.set('')
26 result = None 27 fuhao = None 28 def zhengfu(self): 29 if cuncu[0]: 30 if cuncu[0] == '-':
31 cuncu[0] = '+'
32 elif cuncu[0] == '+':
33 cuncu[0] = '-'
34 else:
35 cuncu.insert(0, '-')
36 vartext.set(''.join(cuncu))
37 def xiaoshudian(self): 38 if cuncu.count('.') >= 1:
39 pass
40 else:
41 if cuncu == [] : 42 cuncu.append('0')
43 cuncu.append('.')
44 vartext.set(''.join(cuncu))
45 def yunshuan(self): 46 global cuncu, vartext, result, fuhao 47 if vartext.get() == '':
48 pass
49 else:
50 get1 = decimal.Decimal(vartext.get()) 51 if self.anjian in ('1/x','sqrt'):
52 if self.anjian == '1/x':
53 result = 1/get1
54 elif self.anjian == 'sqrt':
55 result = math.sqrt(get1) 56 elif self.anjian in ('+','-','','/','='):
57 if fuhao is not None: 58 get1 = decimal.Decimal(result) 59 get2 = decimal.Decimal(vartext.get()) 60 if fuhao == '+':
61 result = get1 + get2 62 elif fuhao == '-':
63 result = get1 - get2 64 elif fuhao == '':
65 result = get1 * get2 66 elif fuhao == '/':
67 result = get1 / get2 68 else:
69 result = get1 70 if self.anjian == '=':
71 fuhao = None 72 else:
73 fuhao = self.anjian 74 print(fuhao)
75 print(result)
76 vartext.set(str(result))
77 cuncu.clear()
78
79 def copy1(): 80 # tkinter.Misc().clipboard_clear()
81 tkinter.Misc().clipboard_append(string(vartext.get()))
82
83 def buju(root): 84 global cuncu, vartext, result, fuhao 85 entry1 = tkinter.Label(root, width=30, height=2, bg='white', anchor='se', textvariable=vartext)
86 entry1.grid(row=0, columnspan=5)
87 buttonMC=tkinter.Button(root,text='MC',width=5)
88 buttonMR=tkinter.Button(root,text='MR',width=5)
89 buttonMS=tkinter.Button(root,text='MS',width=5)
90 buttonM1=tkinter.Button(root,text='M+',width=5)
91 buttonM2=tkinter.Button(root,text='M-',width=5)
92 buttonMC.grid(row=1,column=0)
93 buttonMR.grid(row=1,column=1)
94 buttonMS.grid(row=1,column=2)
95 buttonM1.grid(row=1,column=3)
96 buttonM2.grid(row=1,column=4)
97
98
99 buttonJ=tkinter.Button(root,text='←',width=5,command=anjianzhi('c').tui) 100 buttonCE=tkinter.Button(root,text='CE',width=5) 101 buttonC=tkinter.Button(root,text=' C ',width=5,command=anjianzhi('c').clear) 102 button12=tkinter.Button(root,text='±',width=5,command=anjianzhi('c').zhengfu) 103 buttonD=tkinter.Button(root,text='√',width=5,command=anjianzhi('sqrt').yunshuan) 104 buttonJ.grid(row=2,column=0) 105 buttonCE.grid(row=2,column=1) 106 buttonC.grid(row=2,column=2) 107 button12.grid(row=2,column=3) 108 buttonD.grid(row=2,column=4) 109
110 button7=tkinter.Button(root,text=' 7 ',width=5,command=anjianzhi('7').jia) 111 button8=tkinter.Button(root,text=' 8 ',width=5,command=anjianzhi('8').jia) 112 button9=tkinter.Button(root,text=' 9 ',width=5,command=anjianzhi('9').jia) 113 buttonc=tkinter.Button(root, text=' / ',width=5,command=anjianzhi('/').yunshuan) 114 buttonf= tkinter.Button(root, text=' % ',width=5) 115 button7.grid(row=3,column=0) 116 button8.grid(row=3,column=1) 117 button9.grid(row=3,column=2) 118 buttonc.grid(row=3,column=3) 119 buttonf.grid(row=3,column=4) 120
121 button4=tkinter.Button(root,text=' 4 ',width=5,command=anjianzhi('4').jia) 122 button5=tkinter.Button(root,text=' 5 ',width=5,command=anjianzhi('5').jia) 123 button6=tkinter.Button(root,text=' 6 ',width=5,command=anjianzhi('6').jia) 124 buttonx=tkinter.Button(root,text=' * ',width=5,command=anjianzhi('*').yunshuan) 125 buttonfs=tkinter.Button(root,text='1/x',width=5,command=anjianzhi('1/x').yunshuan) 126 button4.grid(row=4,column=0) 127 button5.grid(row=4,column=1) 128 button6.grid(row=4,column=2) 129 buttonx.grid(row=4,column=3) 130 buttonfs.grid(row=4,column=4) 131
132 button1 = tkinter.Button(root, text=' 1 ',width=5,command=anjianzhi('1').jia) 133 button2 = tkinter.Button(root, text=' 2 ',width=5,command=anjianzhi('2').jia) 134 button3 = tkinter.Button(root, text=' 3 ',width=5,command=anjianzhi('3').jia) 135 button_= tkinter.Button(root, text=' - ',width=5,command=anjianzhi('-').yunshuan) 136 buttondy= tkinter.Button(root, text=' \n = \n ',width=5,command=anjianzhi('=').yunshuan) 137 button1.grid(row=5, column=0) 138 button2.grid(row=5, column=1) 139 button3.grid(row=5, column=2) 140 button_.grid(row=5, column=3) 141 buttondy.grid(row=5, column=4,rowspan=2) 142
143 button0=tkinter.Button(root,text=' 0 ',width=11,command=anjianzhi('0').jia) 144 buttonjh = tkinter.Button(root,text=' . ',width=5,command=anjianzhi('c').xiaoshudian) 145 buttonjia=tkinter.Button(root,text=' + ',width=5,command=anjianzhi('+').yunshuan) 146 button0.grid(row=6,column=0,columnspan=2) 147 buttonjh.grid(row=6,column=2) 148 buttonjia.grid(row=6,column=3) 149 def caidan(root): 150
151 menu=tkinter.Menu(root) 152 submenu1=tkinter.Menu(menu,tearoff=0) 153 menu.add_cascade(label='查看',menu=submenu1) 154 submenu2 = tkinter.Menu(menu, tearoff=0) 155 submenu2.add_command(label='復(fù)制') 156 submenu2.add_command(label='粘貼') 157 menu.add_cascade(label='編輯',menu=submenu2) 158 submenu = tkinter.Menu(menu, tearoff=0) 159 submenu.add_command(label='查看幫助') 160 submenu.add_separator() 161 submenu.add_command(label='關(guān)于計算機(jī)') 162 menu.add_cascade(label='幫助',menu=submenu) 163 root.config(menu=menu) 164
165
166 buju(root) 167 caidan(root) 168 root.mainloop()</pre>