爆肝6小時,只為讓你學會Tkinter!
本文轉自我的博客,原文鏈接https://pumpkin8.com/119.html
Tkinter是一個Python自帶的GUI庫,可以使用他做出一些簡易的GUi界面,使你的Python功能變得可交互,給人一種直觀感受。
由于我手滑給將我做了一晚上的文件刪掉了,所以只能借用B友”曉學森JUN”提供的文件:鏈接:https://pan.baidu.com/s/1glbJTC6EMsRmJAUra9fN9A提取碼:wz7i
1.GUI窗口基本的配置以及如何創(chuàng)建
引入模塊
import tkinter as tk
實例化對象
root = tk.Tk()
窗口的標題
root.title('title')
窗口大小
root.geometry("500x400")
注意,中間是小寫”x“.
顯示窗口
root.mainloop()
2.Tkinter的一些模塊及可選參數
Label
Label標簽用于顯示一些不可修改的文字和圖標。
創(chuàng)建Label
l = tk.Label(root,text="文字",bg='green',font=('Arial,12'),width=15,height=2)
l.pack
參數詳解:
root
是Label標簽要在那個窗口對象的意思。
text
Label標簽顯示的文字,可以為空。
bg
Label標簽的背景顏色。
font
Label標簽顯示的文字的字體和字號。
width
Label標簽的寬度,以字符為單位。
heigth
Label標簽的高度。
擴展:
Label標簽顯示的文字可以修改,并不是一味不變,有一下幾種方式:
1.使用變量
變量必須是使用Tkinter
提供的StringVar
這種字符串變量。如
var = tk.StringVar
然后,并不可以直接寫text=var
而是使用textvariable
。如
textvariable=var
然后,在修改變量時并不能直接賦值,需要使用set命令。如
var.set("內容")
此方法的案例:
import tkinter as tk
root = tk.Tk()
root.title('title')
root.geometry("500x400")
var = tk.StringVar()
l = tk.Label(root,textvariable=var,bg='green',font=('Arial,12'),width=15,height=2)
l.pack()
def hit():
? ?var.set("按鈕被點擊")
b=tk.Button(root,text='按鈕',bg='white',font=("Arial,12"),width=15,height=2,command=hit)
b.pack()
root.mainloop()
可能有一些代碼你不懂,不用擔心,將會在下面繼續(xù)講到。
2.直接使用config
修改
使用此方法,Label標簽可以直接使用text參數而不需要改變。但是修改它必須使用config命令。如
l.config(text="內容" )
此方法不僅適用于修改文字,也可以修改其它的參數。
此模塊的示例代碼
import tkinter as tk
root = tk.Tk()
root.title('title')
root.geometry("500x400")
l = tk.Label(root,text="Label",bg='green',font=('Arial,12'),width=15,height=2)
l.pack()
root.mainloop()
Button
Button是一個按鈕,僅此而已。
創(chuàng)建Button:
b=tk.Button(root,text='按鈕',bg='white',font=("Arial,12"),width=15,height=2,command=hit)
b.pack()
參數詳解:
root
是按鈕要在那個窗口對象的意思。
text
按鈕顯示的文字,可以為空。
bg
按鈕的背景顏色。
font
按鈕顯示的文字的字體和字號。
width
按鈕的寬度,以字符為單位。
heigth
按鈕的高度。
command
按鈕被按下要執(zhí)行的函數指令
擴展:
可以使用config
命令修改參數。如
b.config(修改的參數)
此模塊的示例代碼
import tkinter as tk
root = tk.Tk()
root.title('title')
root.geometry("500x400")
b = tk.Button(root,text="Button",bg='green',font=('Arial,12'),width=15,height=2)
b.pack()
root.mainloop()
Entry
Entry是一個輸入框部件。
創(chuàng)建Entry
e = tk.Entry(root,show=None)
參數詳解:
root
是Entry要在那個窗口對象的意思。
show
是用戶鍵入的文字需要用什么替代,適用于輸入密碼的輸入框。None
表示不用替換,明文顯示,而若想替換,則需使用show="*"
來顯示,當然,*
可以替換。
擴展:
1.需要獲得輸入框的內容,要用到get
命令。如
e.get()
此模塊的示例代碼
import tkinter as tk
root = tk.Tk()
root.title('title')
root.geometry("500x400")
e1 = tk.Entry(root,show=None)
e1.pack()
e2 = tk.Entry(root,show="*")
e2.pack()
root.mainloop()
Text
Text模塊是一個文本框,用戶可以修改里面的內容。
創(chuàng)建Text
t = tk.Text(root,height=2)
參數詳解:
root
是Listbox要在那個窗口對象的意思。
height
文本框能顯示的字符行數,2代表只能顯示兩行的字符。
擴展:
在文本框插入內容,使用insert
。如
t.insert("位置",內容)
位置
插入的位置。insert
是插入到光標后面。end
是插入到最后。
內容
插入的內容。如123或一個變量。
Listbox
Listbox是一個列表,用于顯示內容。
創(chuàng)建Listbox
var2 = tk.StringVar()
var2.set((11,22,33,44))
lb = tk.Listbox(root,listvariable=var2)
lb.pack()
參數詳解:
root
是Listbox要在那個窗口對象的意思。
listvariable
是它要顯示的內容。
擴展:
1.列表末尾插入數據
list_items = [1,2,3,4]
for item in list_items:
? ?lb.insert("end",item)
list_items
是要插入的數據
2.指定列表位置插入數據
lb.insert(位置,'內容')
位置
例如1,2
內容
例如first,second
3.刪除列表指定位置的內容
lb.delete(位置)
位置
例如1,2
此模塊的示例代碼
import tkinter as tk
root = tk.Tk()
root.title('title')
root.geometry("500x400")
var2 = tk.StringVar()
var2.set((11,22,33,44))
lb = tk.Listbox(root,listvariable=var2)
list_items = [1,2,3,4]
lb.pack()
root.mainloop()
Radiobutton
Radiobutton相當于一個單選框。
創(chuàng)建Radiobutton
var = tk.StringVar()
r1 = tk.Radiobutton(root,text='OptionA',
? ? ? ? ? ? ? ? ? ?variable=var,value="A",
? ? ? ? ? ? ? ? ? ?command=print_selection)
r1.pack()
r2 = tk.Radiobutton(root,text='OptionB',
? ? ? ? ? ? ? ? ? ?variable=var,value="B",
? ? ? ? ? ? ? ? ? ?command=print_selection)
r2.pack()
r3 = tk.Radiobutton(root,text='OptionC',
? ? ? ? ? ? ? ? ? ?variable=var,value="C",
? ? ? ? ? ? ? ? ? ?command=print_selection)
r3.pack()
參數詳解:
root
是Radiobutton要在那個窗口對象的意思。
text
是Radiobutton要顯示的文本。
variable=var
相當于把var 變量綁定到Radiobutton。
value
意思是當單選框選中后將此定義的內容傳入綁定的變量。
command
Radiobutton被按下要執(zhí)行的函數指令。
擴展:
要獲得被綁定的變量的內容要用到get
如
var.get()
此模塊的示例代碼
import tkinter as tk
root = tk.Tk()
root.title('title')
root.geometry("500x400")
var = tk.StringVar()
l = tk.Label(root,bg='green',width=25,
? ? ? ? ? ? text="empty")
l.pack()
def print_selection():
? l.config(text="you have selected=>" + var.get())
r1 = tk.Radiobutton(root,text='OptionA',
? ? ? ? ? ? ? ? ? ?variable=var,value="A",
? ? ? ? ? ? ? ? ? ?command=print_selection)
r1.pack()
r2 = tk.Radiobutton(root,text='OptionB',
? ? ? ? ? ? ? ? ? ?variable=var,value="B",
? ? ? ? ? ? ? ? ? ?command=print_selection)
r2.pack()
r3 = tk.Radiobutton(root,text='OptionC',
? ? ? ? ? ? ? ? ? ?variable=var,value="C",
? ? ? ? ? ? ? ? ? ?command=print_selection)
r3.pack()
root.mainloop()
Scale
Scale模塊是一個可拖動的拉動條。
創(chuàng)建Scale
sc = tk.Scale(root,label='try me',from_=0,to=10,orient=tk.HORIZONTAL,length=200,showvalue=0,tickinterval=2,resolution=0.1,command=print_selection)
sc.pack()
參數詳解:
root
是Scale要在那個窗口對象的意思。
label
是scale部件的名稱。
from_=5,to=11
的意思就是從5到11,即這個滾動條最小值為5,最大值為11(這里使用from_是因為在python中有from這個關鍵詞)
orient=tk.HORIZONTAL
在這里就是設置滾動條的方向,這里HORIZONTAL
就是橫向。VERTICAL
就是豎向。
length
這里是指滾動條部件的長度,但注意的是和其他部件width表示不同,width表示的是以字符為單位,比如width=4
,就是4個字符的長度,而此處的length=200
,是指我們常用的像素為單位,即長度為200個像素。
resolution=0.01
此處的0.01就是保留2位小數。0.1就是1位小數。類似數學題。
showvalue
就是在滾動條上方是否顯示提示。showvalue=0
是不顯示,showvalue=1
是顯示。
tickinterval
就是提示格幾個顯示。如tickinterval=2
就是5.00 7.00 ……,tickinterval=3
就是5.00 8.00…..。
此模塊的示例代碼
import tkinter as tk
root = tk.Tk()
root.title('title') ?
root.geometry("500x400")
l = tk.Label(root,bg='green',width=25,
? ? ? ? ? ? text="empty")
l.pack()
def print_selection(v):
? ?l.config(text="you have selected" + v)
sc = tk.Scale(root,label='try me',from_=0,to=10,
? ? ? ? ? ? ?orient=tk.VERTICAL,length=200,
? ? ? ? ? ? ?showvalue=0,tickinterval=2,resolution=0.1,
? ? ? ? ? ? ?command=print_selection)
sc.pack()
root.mainloop()
功能print_selection (v)
,這里的參數v
即拖動條的位置數據。
Checkbutton
Checkbutton與Radiobutton相反,這相當于一個多選框。
創(chuàng)建Checkbutton
var1 = tk.IntVar()
var2 = tk.IntVar()
cb1 = tk.Checkbutton(root,text='Python',variable=var1,
? ? ? ? ? ? ? ? ? ? onvalue=1,offvalue=0,
? ? ? ? ? ? ? ? ? ? command=print_selection)
cb1.pack()
cb2 = tk.Checkbutton(root,text="C++",variable=var2,
? ? ? ? ? ? ? ? ? ? onvalue=1,offvalue=0,
? ? ? ? ? ? ? ? ? ? command=print_selection)
cb2.pack()
參數詳解:
root
是Checkbutton要在那個窗口對象的意思。
text
是Checkbutton要顯示的文本。
variable=var1
相當于把var1 變量綁定到Checkbutton。
onvalue=1
意思是當選框選中后將1傳入綁定的變量。
offvalue=0
意思是當選框未選中將0傳入綁定的變量。
command
Checkbutton被按下要執(zhí)行的函數指令。
擴展:
要獲得被綁定的變量的內容要用到get
如
var.get()
此模塊的示例代碼
import tkinter as tk
root = tk.Tk()
root.title('title') ? ?
root.geometry("500x400")
l = tk.Label(root,bg='green',width=25,
? ? ? ? ? ? text="empty")
l.pack()
def print_selection():
? ?if (var1.get()==1)&(var2.get()==0):
? ? ? ?l.config(text='I love only Python')
? ?elif (var1.get()==0)&(var2.get()==1):
? ? ? ?l.config(text="I love only C++")
? ?elif (var1.get()==0)&(var2.get()==0):
? ? ? ?l.config(text="I don't love either")
? ?else:
? ? ? ?l.config(text='I love both')
var1 = tk.IntVar()
var2 = tk.IntVar()
cb1 = tk.Checkbutton(root,text='Python',variable=var1,
? ? ? ? ? ? ? ? ? ? onvalue=1,offvalue=0,
? ? ? ? ? ? ? ? ? ? command=print_selection)
cb1.pack()
cb2 = tk.Checkbutton(root,text="C++",variable=var2,
? ? ? ? ? ? ? ? ? ? onvalue=1,offvalue=0,
? ? ? ? ? ? ? ? ? ? command=print_selection)
cb2.pack()
root.mainloop()
Canvas
Canvas是一個畫布模塊,你可以在上面放置Gif圖片(我嘗試Jpg,Png都無法放置,有知道的人可以評論指出),和畫出簡易線條等。
創(chuàng)建Canvas
canvas = tk.Canvas(root, bg='blue', height=100, width=200)
canvas.pack()
參數詳解:
root
是Canvas要在那個窗口對象的意思。
bg
就是Canvas的背景顏色。
height
Canvas的高度。
width
Canvas的寬度。
擴展
1.放置Gif圖片
image_file = tk.PhotoImage(file='D:/Code/code/Python/庫/Tkinter/ins.gif')
image = canvas.create_image(10, 10, anchor='nw', image=image_file)
image_file
是一個變量,用于存儲Gif圖片信息。后面的file="路徑"
是圖片的路徑,這里只是我的示例路徑,你可以更改。
10,10
是Gif放在何處的坐標,以anchor
為錨定點,nw,ne,sw,se,e,w,n,s
分別對應左上,右上,左下,右下,右,左,上,下。
2.畫線
x0,y0,x1,y1=50,50,80,80
line = canvas.create_line(x0,y0,x1,y1)
x0,y0,x1,y1
創(chuàng)建變量儲存坐標信息。
?line=canvas.create_line(x0,y0,x1,y1)
畫一條線,從第一個坐標x0,y0畫到第二個坐標x1,y1。
3.畫圓
x0,y0,x1,y1=50,50,80,80
oval = canvas.create_oval(x0,y0,x1,y1,fill='red')
x0,y0,x1,y1
創(chuàng)建變量儲存坐標信息。
oval=canvas.create_oval(x0,y0,c1,y1,fill="red")
畫一個圓,以第一個坐標x0,y0到第二個坐標x1,y1的連線為直徑畫圓,fill="red"
是填充色,紅色。
4.創(chuàng)建矩形
rect = canvas.create_rectangle(100, 30, 100+20, 30+20)
100,30
是起始坐標xy,100+20,30+20
是指,在x坐標100下增加20為長,在y坐標30下增加20為寬。
5.創(chuàng)建扇形
arc = canvas.create_arc(x, y, x+30, y+30, start=0, extent=180)
x,y
是起始坐標。
x+30,y+30
是指在起始坐標上偏移多少做弧線,建議相等,因為這相當于半徑。
start=0
和extent=180
,是指起始角度為0度最終角度是180度。以一個量角器的右邊是0度。
6.移動部件
canvas.move(oval,2,2)
這里以移動圓為案例,在上面,我們把oval
變量用于儲存圓的數據,這里就用到了變量,然后,后面的坐標指在原有的xy坐標上偏移這個值。
此模塊的示例代碼
import tkinter as tk
root = tk.Tk() ?
root.title('title') ? ?
root.geometry("300x200")
canvas = tk.Canvas(root,bg='blue',height=100,width=200)
image_file = tk.PhotoImage(file='D:/Code/code/Python/庫/Tkinter/ins.gif')
image = canvas.create_image(30, 30, anchor='w', image=image_file)
x0,y0,x1,y1=50,50,80,80
line = canvas.create_line(x0,y0,x1,y1)
oval = canvas.create_oval(x0,y0,x1,y1,fill='red')
rect = canvas.create_rectangle(100, 30, 100+20, 30+50)
arc = canvas.create_arc(x0, y0, x1+30, y1+30, start=0, extent=180)
canvas.pack()
def moveit():
? ?canvas.move(oval,2,2)
b = tk.Button(root,text='move',command=moveit).pack()
root.mainloop()
Menu
Meun模塊是一個菜單欄模塊,存在于窗口頂部,用于用戶交互。點我查看示例圖片
首先,我們創(chuàng)建一個菜單容器,就是圖片的頂部那一個長條,用于存放菜單選項。
menu = tk.Menu(root)
root.config(menu=menu)
參數詳解:
root
就是Menu要放在那個窗口的意思。
root.config(menu=menu)
是指,將窗口root
的菜單欄設為我們設好的菜單容器(左邊的menu
),因為重名所以有點別扭。
隨后,在創(chuàng)建一個菜單選項,就是圖中file,edit選項。
file_menu = tk.Menu(menu, tearoff=0)
參數詳解:
menu
?就這個菜單選項要放在哪一個菜單容器里。
tearoff
就是它能不能被分開。0是不能,1是能。建議不能,若允許分開,點擊菜單選項會新建彈窗。
把這個菜單選項加進menu
的菜單容器內。
menu.add_cascade(label='File', menu=file_menu)
參數詳解:
label
是指這個選項要在容器內顯示什么名字。
menu
是指把啥菜單選項添加進這個容器內。
最后,在這個菜單選項里增加功能選項。
file_menu.add_cascade(label='New', command=do_job)
參數詳解:
label
是指這個功能要顯示什么名字。
command
當這個選項被按下要執(zhí)行的函數指令。
擴展
1.在菜單選項中增加分割線,使用add_separator()
命令。如
file_menu.add_separator()
2.在菜單 選項中套娃。
就是將一個菜單選項定義成一個容器,在里面放置一個菜單選項。
submenu = tk.Menu(file_menu)
file_menu.add_cascade(label='import', menu=submenu,underline=0)
submenu.add_command(label='Submenu', command=do_job)
underline
只是一個參數,暫時不用管。
此模塊的示例代碼
root = tk.Tk() ?
root.title('title') ? ?
root.geometry("300x200")
lb = tk.Label(root,text=' ? ', bg='yellow')
lb.pack()
count = 0
def do_job():
? ?global count
? ?lb.config(text='do'+str(count))
? ?count += 1
menu = tk.Menu(root)
file_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='File', menu=file_menu)
file_menu.add_cascade(label='New', command=do_job)
file_menu.add_cascade(label='Open', command=do_job)
file_menu.add_cascade(label='Save', command=do_job)
file_menu.add_cascade(label='Delete', command=do_job)
file_menu.add_separator()
file_menu.add_cascade(label='Exit', command=root.quit)
edit_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='Edit', menu=edit_menu)
edit_menu.add_cascade(label='Cut', command=do_job)
edit_menu.add_cascade(label='Copy', command=do_job)
edit_menu.add_cascade(label='Paste', command=do_job)
submenu = tk.Menu(file_menu)
file_menu.add_cascade(label='import', menu=submenu,underline=0)
submenu.add_command(label='Submenu', command=do_job)
root.config(menu=menu)
root.mainloop()
Frame
Frame相當于是窗口中的窗口,可以顯示一些部件,可以合理規(guī)劃位置。
創(chuàng)建主Frame
frm = tk.Frame(root)
frm.pack()
參數詳解:
root
就是Frame要在那個窗口的意思。
在主Frame中創(chuàng)建兩個Frame模塊。
frm_l = tk.Frame(frm)
frm_r = tk.Frame(frm)
frm
就是這兩個Frame要在那個Frame模塊中。
隨后,設置這些Frame的位置。
frm_l.pack(side='left')
frm_r.pack(side='right')
side
就是在那個方位。暫時只試出left
,right
,top
這些,如果你了解的話可以評論指出。
最后,在Frame中加入模塊。
tk.Label(frm_l,text='on the frm_l1').pack()
tk.Label(frm_l,text='on the frm_l2').pack()
tk.Label(frm_r,text='on the frm_rl').pack()
frm_l
?就是這些部件要在哪個Frame中。
此模塊示例代碼
import tkinter as tk
root = tk.Tk() ?
root.title('title') ? ?
root.geometry("300x200")
tk.Label(root,text='on the windows').pack()
frm = tk.Frame(root)
frm.pack()
frm_l = tk.Frame(frm)
frm_r = tk.Frame(frm)
frm_l.pack(side='left')
frm_r.pack(side='right')
tk.Label(frm_l,text='on the frm_l1').pack()
tk.Label(frm_l,text='on the frm_l2').pack()
tk.Label(frm_r,text='on the frm_rl').pack()
root.mainloop()
Messagebox
Messagebox是一個彈窗部件,用于提醒消息,報錯,警告,選擇。
使用這個模塊,需要額外引用庫。
import tkinter.messagebox
創(chuàng)建消息框
tkinter.messagebox.showinfo(title='八個南瓜', message='pumpkin8.com')
創(chuàng)建警告框
tkinter.messagebox.showwarning(title='八個南瓜', message='pumpkin8.com')
創(chuàng)建錯誤框
tkinter.messagebox.showerror(title='八個南瓜', message='pumpkin8.com')
創(chuàng)建選擇框
tkinter.messagebox.askquestion(title='八個南瓜', message='pumpkin8.com')
參數詳解:
title
就是窗口名稱
message
就是內容
擴展
可以使用print
來輸入用戶選項,也可以變量賦值。
此模塊的示例代碼
import tkinter as tk
import tkinter.messagebox
root = tk.Tk()
root.title('title') ? ?
root.geometry("300x200")
def hit():
? ?tkinter.messagebox.showinfo(title='Hi', message='你好')
? ?tkinter.messagebox.showwarning(title='八個南瓜', message='pumpkin8.com')
? ?tkinter.messagebox.showerror(title='八個南瓜', message='pumpkin8.com')
? ?tkinter.messagebox.askquestion(title='八個南瓜', message='pumpkin8.com')
tk.Button(root, text='hit', width=10,height=2, command=hit).pack()
root.mainloop()
模塊放置位置
模塊放置的方法有三種。
1.Pack
tk.Label(window, text='1').pack(side='top')#上
tk.Label(window, text='1').pack(side='bottom')#下
tk.Label(window, text='1').pack(side='left')#左
tk.Label(window, text='1').pack(side='right')#右
2.grid
我運行報錯,有知道的可以評論指出
for i in range(4):
? ?for j in range(3):
? ? ? ?tk.Label(window, text=1).grid(row=i, column=j, padx=10, pady=10)
3.Place
tk.Label(window, text=1).place(x=20, y=10, anchor='nw')
anchor
指錨定點。
本文檔到此結束
以上教程都是博主學習后總結而來,如果有錯誤的地方,歡迎評論指出錯誤。