Python?GUI布局工具Tkinter入門之旅
圖形用戶界面 (GUI)
圖形用戶界面 (GUI) 只不過(guò)是一個(gè)桌面應(yīng)用程序,可幫助我們與計(jì)算機(jī)進(jìn)行交互
- 像文本編輯器這樣的 GUI 應(yīng)用程序可以創(chuàng)建、讀取、更新和刪除不同類型的文件
- 數(shù)獨(dú)、國(guó)際象棋和紙牌等應(yīng)用程序則是游戲版的GUI程序
- 還有 Google Chrome、Firefox 和 Microsoft Edge 之類的 GUI 應(yīng)用程序是用來(lái)瀏覽 Internet 的
這些都是我們?nèi)粘T陔娔X上使用的一些不同類型的 GUI 應(yīng)用程序,其實(shí)我們通過(guò) Tkinter 也是可以構(gòu)建簡(jiǎn)單的類似應(yīng)用程序的
今天我們作為 GUI 的入門,將創(chuàng)建一個(gè)非常簡(jiǎn)單且漂亮的 GUI 應(yīng)用程序
用于創(chuàng)建GUI的 Python 庫(kù)
Python 有大量的第三方類庫(kù),對(duì)于 GUI 庫(kù),主要有以下幾種:
- Kivy
- Python QT
- wxPython
- Tkinter
其中,Tkinter 是很多學(xué)習(xí)者和開(kāi)發(fā)者的首選,因?yàn)樗?jiǎn)單易用而且隨 Python 安裝自帶
Tkinter 基礎(chǔ)
下面的圖片顯示了應(yīng)用程序是如何在 Tkinter 中實(shí)際執(zhí)行
我們首先導(dǎo)入 Tkinter 模型,接著,我們創(chuàng)建主窗口,在這個(gè)窗口中,我們將要執(zhí)行操作并顯示一切視覺(jué)效果,接下來(lái)我們添加 Widgets,最后我們進(jìn)入 Main Event Loop
這里有 2 個(gè)重要的關(guān)鍵字
- Widgets
- Main Event Loop
事件循環(huán)基本上是告訴代碼繼續(xù)顯示窗口,直到我們手動(dòng)關(guān)閉它,是在后臺(tái)無(wú)限循環(huán)運(yùn)行的
對(duì)于 Widgets 我們后面單獨(dú)學(xué)習(xí)
下面一個(gè)代碼例子,來(lái)深入理解下
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 包并定義一個(gè)窗口,接著我們可以修改一個(gè)窗口標(biāo)題,每當(dāng)打開(kāi)應(yīng)用程序時(shí),該標(biāo)題都會(huì)顯示在標(biāo)題選項(xiàng)卡上
最后,我們還定義了一個(gè)標(biāo)簽,標(biāo)簽只不過(guò)是需要在窗口上顯示的輸出,在例子中是 hello world
Tkinter Widgets
那么到底什么是 Widgets 呢
Widgets 類似于 HTML 中的元素,我們可以在 Tkinter 中找到針對(duì)不同類型元素的不同類型的 Widgets
讓我們看看 Tkinter 中所有這些 Widgets 的簡(jiǎn)要介紹
- 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)建菜單
下面讓我們逐一看一下每個(gè) Widgets 的用法
Label
標(biāo)簽用于創(chuàng)建文本和圖像以及所有相關(guān)的,而且要注意的是,它只能是單行定義
l1 = Label(window, text="蘿卜大雜燴!", font=("ArialBold", 50)) l1.grid(column=0, row=0)
還有一個(gè)函數(shù) geometry,它基本上用于更改窗口大小并根據(jù)我們的要求進(jìn)行設(shè)置
l1 = Label(window, text="蘿卜大雜燴!", font=("ArialBold", 50)) window.geometry('350x200')
在這種情況下,我們將其設(shè)置為寬 350 像素和高 200 像素
接下來(lái)是 button
Button
按鈕與標(biāo)簽非常相似,我們創(chuàng)建一個(gè)變量并使用 Widgets 語(yǔ)法來(lái)定義按鈕要表達(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)
我們的前景是定義為紅色的文本,背景為橙色
下面來(lái)看一下點(diǎn)擊按鈕的操作
def clicked(): l1.configure(text="按鈕被點(diǎn)擊了!!") bt = Button(window, text="Enter", bg="orange", fg="red", command=clicked)
這個(gè)我們稱之為點(diǎn)擊事件,我們需要編寫有關(guān)單擊按鈕或觸發(fā)單擊事件時(shí)應(yīng)該發(fā)生什么的功能
我們定義了一個(gè)名為 clicked 的函數(shù),可以顯示一條文本消息,我們?cè)诎粹o定義中添加一個(gè)名為 command 的參數(shù),來(lái)調(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)建一個(gè)文本框,grid 定義我們希望窗口小部件位于何處
同時(shí) clicked 函數(shù)接收 Entry 的文本信息
Combobox
這是一個(gè)帶有某些選項(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)
這樣一個(gè)下拉菜單就完成了
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)建一個(gè) booleanvar 類型的變量,這是一個(gè) Tkinter 變量
默認(rèn)情況下,我們將設(shè)置狀態(tài)保持為 true,這代表按鈕已經(jīng)被選中 接下來(lái),我們將 chk_state 傳遞給 checkbutton 類來(lái)為我們?cè)O(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,如果它們相同,則會(huì)導(dǎo)致沖突并出現(xiàn)錯(cuò)誤
它們的文本數(shù)據(jù)是可以相同,在這里,我們使用了 Python、Java 和 Scala
Scrolled Text
滾動(dòng)文本組件
scro_txt = scrolledtext.ScrolledText(window, width=40,height=10) scro_txt.grid(column=0, row=4)
我們指定了窗口的高和寬,否則默認(rèn)會(huì)填充整個(gè) Windiws 窗口
Message Box
消息組件可以方便的彈出提醒消息
def clicked(): messagebox.showinfo('Message title', 'Message content') btn = Button(window,text=‘ENTER', command=clicked)
SpinBox
Spinbox 也是一個(gè)常見(jiàn)的組件,有兩個(gè)選項(xiàng)卡,存在向上和向下滾動(dòng)選項(xiàng)卡
pin = Spinbox(window, from_=0, to=100, width=5)
有 3 個(gè)參數(shù)——from、to 和 width
- From – 告訴我們范圍的開(kāi)始和默認(rèn)值
- to – 給我們范圍的上限閾值
- width 基本上是將 widget 的大小設(shè)置為5個(gè)字符的空格
Geometry
Tkinter 中的所有 Widgets 都會(huì)有一些位置信息,這些度量使得我們可以組織 Widgets 及其父框架、窗口等
Tkinter 具有以下三個(gè)布局方式
- pack():- 它在塊中組織 Widgets,這意味著它占據(jù)了整個(gè)可用寬度,這是在窗口中顯示 Widgets 的標(biāo)準(zhǔn)方法
- grid():- 它以類似表格的結(jié)構(gòu)組織 Widgets
- place():- 它將 Widgets 放置在我們想要的特定位置
組織布局
為了在窗口中安排布局,我們將使用 Frame 類
- Frame -- 在窗口中創(chuàng)建分區(qū),我們可以根據(jù)需要使用 pack() 方法的側(cè)面參數(shù)對(duì)齊框架
- Button -- 在窗口中創(chuàng)建一個(gè)按鈕,需要傳遞幾個(gè)參數(shù),如文本(按鈕的值)、fg(文本的顏色)、bg(背景顏色)
在下面的代碼中,我們使用 window、top_frame、bottom_frame 來(lái)布局
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()
再來(lái)看一個(gè)登錄的小栗子
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()
下面我們來(lái)了解 binding 函數(shù)
binding 函數(shù)
每當(dāng)事件發(fā)生時(shí)調(diào)用函數(shù)就是綁定函數(shù)
在下面的示例中,當(dāng)單擊按鈕時(shí),它會(huì)調(diào)用一個(gè)名為 say_hi 的函數(shù)。 函數(shù) say_hi 會(huì)創(chuàng)建一個(gè)帶有文本 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)移動(dòng)、鼠標(biāo)懸停、單擊和滾動(dòng)等等
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
下面的代碼將使用對(duì)于的文本創(chuàng)建一個(gè)新標(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í)我們都梳理完畢了,下面就完成一個(gè)簡(jiǎn)單的實(shí)戰(zhàn)項(xiàng)目吧
計(jì)算器 APP
首先初始化頁(yè)面
window = Tk() window.geometry("350x380") window.resizable(0, 0) # this prevents from resizing the window window.title("小小計(jì)算器")
接下來(lái)定義輸入數(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)
最后就是計(jì)算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è)面很簡(jiǎn)陋,但是加減乘除這些基本運(yùn)算還是包含了的
以上就是Python GUI布局工具Tkinter入門之旅的詳細(xì)內(nèi)容,更多關(guān)于Python GUI布局Tkinter的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python網(wǎng)絡(luò)爬蟲(chóng)精解之pyquery的使用說(shuō)明
PyQuery是一個(gè)類似于jQuery的解析網(wǎng)頁(yè)工具,使用lxml操作xml和html文檔,它的語(yǔ)法和jQuery很像。和XPATH,Beautiful Soup比起來(lái),PyQuery更加靈活,提供增加節(jié)點(diǎn)的class信息,移除某個(gè)節(jié)點(diǎn),提取文本信息等功能2021-09-09Django自定義分頁(yè)與bootstrap分頁(yè)結(jié)合
這篇文章主要為大家詳細(xì)介紹了Django自定義分頁(yè)與bootstrap分頁(yè)結(jié)合使用的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05python導(dǎo)出hive數(shù)據(jù)表的schema實(shí)例代碼
這篇文章主要介紹了python導(dǎo)出hive數(shù)據(jù)表的schema實(shí)例代碼,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01教你怎么用Python操作MySql數(shù)據(jù)庫(kù)
很多小伙伴都在問(wèn)我能不能出一篇怎么用Python操作MySql數(shù)據(jù)庫(kù)的教程,今天特地整理了本篇文章,文中有非常詳細(xì)的圖文示例,需要的朋友可以參考下2021-05-05python str字符串轉(zhuǎn)uuid實(shí)例
這篇文章主要介紹了python str字符串轉(zhuǎn)uuid實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03Selenium?4.2.0?標(biāo)簽定位8種方法詳解
這篇文章主要介紹了Selenium?4.2.0?標(biāo)簽定位8種方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06Python3.10?Generator生成器Coroutine原生協(xié)程詳解
這篇文章主要為大家介紹了Python3.10?Generator生成器Coroutine原生協(xié)程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12python Jieba分詞處理詳解【模式,詞庫(kù)的添加、刪除,自定義詞庫(kù),失敗處理等】
這篇文章主要介紹了python Jieba分詞處理,結(jié)合實(shí)例形式詳細(xì)分析了python 使用jieba分詞的模式,詞庫(kù)的添加、刪除,自定義詞庫(kù),失敗處理等相關(guān)操作技巧,需要的朋友可以參考下2023-07-07使用Python腳本對(duì)Linux服務(wù)器進(jìn)行監(jiān)控的教程
這篇文章主要介紹了使用Python程序?qū)inux服務(wù)器進(jìn)行監(jiān)控的教程,主要基于Python2.7的版本,需要的朋友可以參考下2015-04-04詳解Python3 對(duì)象組合zip()和回退方式*zip
這篇文章主要介紹了Python3 對(duì)象組合zip()和回退方式*zip詳解,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05