Python?GUI布局工具Tkinter入門之旅
圖形用戶界面 (GUI)
圖形用戶界面 (GUI) 只不過是一個桌面應(yīng)用程序,可幫助我們與計算機(jī)進(jìn)行交互
- 像文本編輯器這樣的 GUI 應(yīng)用程序可以創(chuàng)建、讀取、更新和刪除不同類型的文件
- 數(shù)獨(dú)、國際象棋和紙牌等應(yīng)用程序則是游戲版的GUI程序
- 還有 Google Chrome、Firefox 和 Microsoft Edge 之類的 GUI 應(yīng)用程序是用來瀏覽 Internet 的
這些都是我們?nèi)粘T陔娔X上使用的一些不同類型的 GUI 應(yīng)用程序,其實(shí)我們通過 Tkinter 也是可以構(gòu)建簡單的類似應(yīng)用程序的
今天我們作為 GUI 的入門,將創(chuàng)建一個非常簡單且漂亮的 GUI 應(yīng)用程序
用于創(chuàng)建GUI的 Python 庫
Python 有大量的第三方類庫,對于 GUI 庫,主要有以下幾種:
- Kivy
- Python QT
- wxPython
- Tkinter
其中,Tkinter 是很多學(xué)習(xí)者和開發(fā)者的首選,因?yàn)樗唵我子枚译S Python 安裝自帶
Tkinter 基礎(chǔ)
下面的圖片顯示了應(yīng)用程序是如何在 Tkinter 中實(shí)際執(zhí)行

我們首先導(dǎo)入 Tkinter 模型,接著,我們創(chuàng)建主窗口,在這個窗口中,我們將要執(zhí)行操作并顯示一切視覺效果,接下來我們添加 Widgets,最后我們進(jìn)入 Main Event Loop
這里有 2 個重要的關(guān)鍵字
- Widgets
- Main Event Loop
事件循環(huán)基本上是告訴代碼繼續(xù)顯示窗口,直到我們手動關(guān)閉它,是在后臺無限循環(huán)運(yùn)行的
對于 Widgets 我們后面單獨(dú)學(xué)習(xí)
下面一個代碼例子,來深入理解下
import tkinter
window = tkinter.Tk()
# to rename the title of the window window.title("GUI")
# pack is used to show the object in the window
label = tkinter.Label(window, text = "Hello World!").pack()
window.mainloop()
我們導(dǎo)入 Tkinter 包并定義一個窗口,接著我們可以修改一個窗口標(biāo)題,每當(dāng)打開應(yīng)用程序時,該標(biāo)題都會顯示在標(biāo)題選項(xiàng)卡上
最后,我們還定義了一個標(biāo)簽,標(biāo)簽只不過是需要在窗口上顯示的輸出,在例子中是 hello world

Tkinter Widgets
那么到底什么是 Widgets 呢
Widgets 類似于 HTML 中的元素,我們可以在 Tkinter 中找到針對不同類型元素的不同類型的 Widgets
讓我們看看 Tkinter 中所有這些 Widgets 的簡要介紹

- Canvas - Canvas 用于在 GUI 中繪制形狀
- Button – Button 用于在 Tkinter 中放置按鈕
- Checkbutton – Checkbutton 用于在應(yīng)用程序中創(chuàng)建復(fù)選按鈕
- Entry - Entry 用于在 GUI 中創(chuàng)建輸入字段
- Frame – Frame 在 Tkinter 中用作容器
- Label - Label 用于創(chuàng)建單行 Widgets,如文本、圖像等
- Menu - Menu 用于在 GUI 中創(chuàng)建菜單
下面讓我們逐一看一下每個 Widgets 的用法
Label
標(biāo)簽用于創(chuàng)建文本和圖像以及所有相關(guān)的,而且要注意的是,它只能是單行定義
l1 = Label(window, text="蘿卜大雜燴!", font=("ArialBold", 50))
l1.grid(column=0, row=0)

還有一個函數(shù) geometry,它基本上用于更改窗口大小并根據(jù)我們的要求進(jìn)行設(shè)置
l1 = Label(window, text="蘿卜大雜燴!", font=("ArialBold", 50))
window.geometry('350x200')
在這種情況下,我們將其設(shè)置為寬 350 像素和高 200 像素
接下來是 button
Button
按鈕與標(biāo)簽非常相似,我們創(chuàng)建一個變量并使用 Widgets 語法來定義按鈕要表達(dá)的內(nèi)容
window.geometry('350x200')
bt = Button(window, text="Enter")

我們還可以更改按鈕或任何其他 Widgets 的前景顏色,使用代碼中所示的參數(shù) FG。 同樣,也可以使用 BG 屬性更改背景顏色
bt = Button(window, text="Enter", bg="orange", fg="red") bt.grid(column=1, row=0)

我們的前景是定義為紅色的文本,背景為橙色
下面來看一下點(diǎn)擊按鈕的操作
def clicked():
l1.configure(text="按鈕被點(diǎn)擊了!!")
bt = Button(window, text="Enter", bg="orange", fg="red", command=clicked)
這個我們稱之為點(diǎn)擊事件,我們需要編寫有關(guān)單擊按鈕或觸發(fā)單擊事件時應(yīng)該發(fā)生什么的功能
我們定義了一個名為 clicked 的函數(shù),可以顯示一條文本消息,我們在按鈕定義中添加一個名為 command 的參數(shù),來調(diào)用點(diǎn)擊事件

Entry
它用于在 GUI 中創(chuàng)建輸入字段以接收文本輸入
txt = Entry(window, width=10)
txt.grid(column=1, row=0)
def clicked():
res = "Welcome to " + txt.get()
l1.configure(text=res)
bt = Button(window, text="Enter", bg="orange", fg="red", command=clicked)
在這里,我們使用 Tkinter Entry 類創(chuàng)建一個文本框,grid 定義我們希望窗口小部件位于何處
同時 clicked 函數(shù)接收 Entry 的文本信息

Combobox
這是一個帶有某些選項(xiàng)的下拉菜單
from tkinter.ttk import * combo = Combobox(window) combo['values']= (1, 2, 3, 4, 5, "Text") combo.current(3) combo.grid(column=0, row=0)

這樣一個下拉菜單就完成了
Checkbutton
復(fù)選按鈕是非常常用的組件
chk_state = BooleanVar() chk_state.set (True) chk = Checkbutton(window, text="Select", var=chk_state) chk.grid(column=4, row=0)
我們首先創(chuàng)建一個 booleanvar 類型的變量,這是一個 Tkinter 變量
默認(rèn)情況下,我們將設(shè)置狀態(tài)保持為 true,這代表按鈕已經(jīng)被選中 接下來,我們將 chk_state 傳遞給 checkbutton 類來為我們設(shè)置檢查狀態(tài)

Radio Button
單選按鈕也是非常常用的
rad1 = Radiobutton(window, text=Python', value=1) rad2 = Radiobutton(window, text=Java', value=2) rad3 = Radiobutton(window, text=Scala', value=3) rad1.grid(column=0, row=0) rad2.grid(column=1, row=0) rad3.grid(column=2, row=0)
在這里,我們使用了不同的參數(shù)值,1,2和3,如果它們相同,則會導(dǎo)致沖突并出現(xiàn)錯誤
它們的文本數(shù)據(jù)是可以相同,在這里,我們使用了 Python、Java 和 Scala

Scrolled Text
滾動文本組件
scro_txt = scrolledtext.ScrolledText(window, width=40,height=10) scro_txt.grid(column=0, row=4)
我們指定了窗口的高和寬,否則默認(rèn)會填充整個 Windiws 窗口

Message Box
消息組件可以方便的彈出提醒消息
def clicked():
messagebox.showinfo('Message title', 'Message content')
btn = Button(window,text=‘ENTER', command=clicked)

SpinBox
Spinbox 也是一個常見的組件,有兩個選項(xiàng)卡,存在向上和向下滾動選項(xiàng)卡
pin = Spinbox(window, from_=0, to=100, width=5)
有 3 個參數(shù)——from、to 和 width
- From – 告訴我們范圍的開始和默認(rèn)值
- to – 給我們范圍的上限閾值
- width 基本上是將 widget 的大小設(shè)置為5個字符的空格

Geometry
Tkinter 中的所有 Widgets 都會有一些位置信息,這些度量使得我們可以組織 Widgets 及其父框架、窗口等
Tkinter 具有以下三個布局方式
- pack():- 它在塊中組織 Widgets,這意味著它占據(jù)了整個可用寬度,這是在窗口中顯示 Widgets 的標(biāo)準(zhǔn)方法
- grid():- 它以類似表格的結(jié)構(gòu)組織 Widgets
- place():- 它將 Widgets 放置在我們想要的特定位置
組織布局
為了在窗口中安排布局,我們將使用 Frame 類
- Frame -- 在窗口中創(chuàng)建分區(qū),我們可以根據(jù)需要使用 pack() 方法的側(cè)面參數(shù)對齊框架
- Button -- 在窗口中創(chuàng)建一個按鈕,需要傳遞幾個參數(shù),如文本(按鈕的值)、fg(文本的顏色)、bg(背景顏色)
在下面的代碼中,我們使用 window、top_frame、bottom_frame 來布局
import tkinter
window = tkinter.Tk()
window.title("GUI")
# creating 2 frames TOP and BOTTOM
top_frame = tkinter.Frame(window).pack()
bottom_frame = tkinter.Frame(window).pack(side = "bottom")
# now, create some widgets in the top_frame and bottom_frame
btn1 = tkinter.Button(top_frame, text = "Button1", fg = "red").pack()# 'fg - foreground' is used to color the contents
btn2 = tkinter.Button(top_frame, text = "Button2", fg = "green").pack()# 'text' is used to write the text on the Button
btn3 = tkinter.Button(bottom_frame, text = "Button2", fg = "purple").pack(side = "left")# 'side' is used to align the widgets
btn4 = tkinter.Button(bottom_frame, text = "Button2", fg = "orange").pack(side = "left")
window.mainloop()

再來看一個登錄的小栗子
import tkinter
window = tkinter.Tk()
window.title("GUI")
# creating 2 text labels and input labels
tkinter.Label(window, text = "Username").grid(row = 0) # this is placed in 0 0
# 'Entry' is used to display the input-field
tkinter.Entry(window).grid(row = 0, column = 1) # this is placed in 0 1
tkinter.Label(window, text = "Password").grid(row = 1) # this is placed in 1 0
tkinter.Entry(window).grid(row = 1, column = 1) # this is placed in 1 1
# 'Checkbutton' is used to create the check buttons
tkinter.Checkbutton(window, text = "Keep Me Logged In").grid(columnspan = 2) # 'columnspan' tells to take the width of 2 columns
# you can also use 'rowspan' in the similar manner
window.mainloop()

下面我們來了解 binding 函數(shù)
binding 函數(shù)
每當(dāng)事件發(fā)生時調(diào)用函數(shù)就是綁定函數(shù)
在下面的示例中,當(dāng)單擊按鈕時,它會調(diào)用一個名為 say_hi 的函數(shù)。 函數(shù) say_hi 會創(chuàng)建一個帶有文本 Hi 的新標(biāo)簽
import tkinter
window = tkinter.Tk()
window.title("GUI")
# creating a function called say_hi()
def say_hi():
tkinter.Label(window, text = "Hi").pack()
tkinter.Button(window, text = "Click Me!", command = say_hi).pack() # 'command' is executed when you click the button
# in this above case we're calling the function 'say_hi'.
window.mainloop()

另一種綁定函數(shù)的方法是使用事件,事件類似于鼠標(biāo)移動、鼠標(biāo)懸停、單擊和滾動等等
import tkinter
window = tkinter.Tk()
window.title("GUI")
# creating a function with an arguments 'event'
def say_hi(event): # you can rename 'event' to anything you want
tkinter.Label(window, text = "Hi").pack()
btn = tkinter.Button(window, text = "Click Me!")
btn.bind("Button-1", say_hi) # 'bind' takes 2 parameters 1st is 'event' 2nd is 'function'
btn.pack()
window.mainloop()
單擊事件有 3 種不同的類型,分別是 leftClick、middleClick 和 rightClick
下面的代碼將使用對于的文本創(chuàng)建一個新標(biāo)簽
import tkinter
window = tkinter.Tk()
window.title("GUI")
#creating 3 different functions for 3 events
def left_click(event):
tkinter.Label(window, text = "Left Click!").pack()
def middle_click(event):
tkinter.Label(window, text = "Middle Click!").pack()
def right_click(event):
tkinter.Label(window, text = "Right Click!").pack()
window.bind("Button-1", left_click)
window.bind("Button-2", middle_click)
window.bind("Button-3", right_click)
window.mainloop()

Images 和 Icons
我們可以使用 PhotoImage 方法添加圖像和圖標(biāo)
import tkinter
window = tkinter.Tk()
window.title("GUI")
# taking image from the directory and storing the source in a variable
icon = tkinter.PhotoImage(file = "4.PNG")
# displaying the picture using a 'Label' by passing the 'picture' variriable to 'image' parameter
label = tkinter.Label(window, image = icon)
label.pack()
window.mainloop()

好了,進(jìn)步的 Tkinter 知識我們都梳理完畢了,下面就完成一個簡單的實(shí)戰(zhàn)項(xiàng)目吧
計算器 APP
首先初始化頁面
window = Tk()
window.geometry("350x380")
window.resizable(0, 0) # this prevents from resizing the window
window.title("小小計算器")
接下來定義輸入數(shù)字框
input_text = StringVar()
input_frame = Frame(window, width=312, height=50, bd=0, highlightbackground="black", highlightcolor="black",
highlightthickness=1)
input_frame.pack(side=TOP)
input_field = Entry(input_frame, font=('arial', 18, 'bold'), textvariable=input_text, width=50, bg="#eee", bd=0,
justify=RIGHT)
input_field.grid(row=0, column=0)
input_field.pack(ipady=10)
然后定義按鈕方法,我們以清除按鈕和除法按鈕為例
clear = Button(btns_frame, text="C", fg="black", width=32, height=3, bd=0, bg="#eee", cursor="hand2",
command=lambda: btn_clear()).grid(row=0, column=0, columnspan=3, padx=1, pady=1)
divide = Button(btns_frame, text="/", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2",
command=lambda: btn_click("/")).grid(row=0, column=3, padx=1, pady=1)
最后就是計算equal邏輯
equals = Button(btns_frame, text="=", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2",
command=lambda: btn_equal()).grid(row=4, column=3, padx=1, pady=1)
def btn_equal():
global expression
result = str(eval(expression))
input_text.set(result)
expression = ""
好了,讓我看下最終的效果吧,雖然頁面很簡陋,但是加減乘除這些基本運(yùn)算還是包含了的

以上就是Python GUI布局工具Tkinter入門之旅的詳細(xì)內(nèi)容,更多關(guān)于Python GUI布局Tkinter的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Django Docker容器化部署之Django-Docker本地部署
這篇文章主要介紹了Django Docker容器化部署之Django-Docker本地部署,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
Python使用execjs模塊運(yùn)行JavaScript代碼
在編程中,Python和JavaScript是兩種使用廣泛的編程語言,本文將深入探索如何通過execjs模塊在Python中運(yùn)行JavaScript代碼,有需要的可以參考一下2025-03-03
python爬取本站電子書信息并入庫的實(shí)現(xiàn)代碼
這篇文章主要介紹了python爬取本站電子書信息并入庫的實(shí)現(xiàn)代碼,需要的朋友可以參考下2020-01-01
win10系統(tǒng)下Anaconda3安裝配置方法圖文教程
這篇文章主要為大家詳細(xì)介紹了win10系統(tǒng)下Anaconda3安裝配置方法圖文教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09
Python PCA降維的兩種實(shí)現(xiàn)方法
大家好,本篇文章主要講的是Python PCA降維的兩種實(shí)現(xiàn)方法,感興趣的的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01
Numpy截取指定范圍內(nèi)的數(shù)據(jù)方法
今天小編就為大家分享一篇Numpy截取指定范圍內(nèi)的數(shù)據(jù)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11

