8000 字,詳解 Tkinter 的 GUI 界面製作!
本文爲大家講述瞭如何使用Tkinter
製作一個簡單的可視化界面工具。有時候,我們用代碼實現了某些功能,如果可以爲這個功能添加一個界面,是否會感覺很棒?
在正式講述文章之前,先來看看使用Tkinter
做出來的最終效果吧!
Tkinter 簡介
Tkinter
(也叫 Tk 接口) 是 Tk 圖形用戶界面工具包標準 的 Python 接口。
Tk 是一個輕量級的跨平臺圖形用戶界面 (GUI) 開發工具。Tk 和 Tkinter 可以運行在大多數 的 Unix 平臺、Windows、和 Macintosh 系統。
由於Tkinter
是 Python 自帶的標準庫,我們想要使用它的時候,只需直接導入即可。
from tkinter import *
Tkinter
支持的組件有:
Tkinter 常用組件使用介紹
上述爲大家列出了Tkinter
中的常用組件。各個組件有其相對應的功能和用法,而我們可以根據我這些控件自由組合
來展現出我們想要的效果。
這裏先給大家簡單介紹一下常用的,也是本文小工具
裏會用到的一些組件。
1. Button(按鈕控件)
Button 組件是用來觸發事件的,它會在窗口上以按鈕的方式顯示,在你單擊它的時候就會運行與 Button 綁定的函數。
from tkinter import *
def b1():
root['bg'] = "blue"
root = Tk()
str1 = "Hello World"
Button(root,text = str1,command = b1).place(x=0,y=0)
root.mainloop()
效果如下:
2. Label(標籤控件)
Label 是標籤控件,能在指定的窗口中顯示的文本和圖像。
from tkinter import *
root = Tk()
str1 = "Hello World"
Label(root,text=str1).place(x=0,y=0)
root.mainloop()
效果如下:
3. Entry(文本框)
Entry 是文本框,用來讓用戶輸入一行文本字符串,也可以用來顯示文本字符串。在使用 Entry 的時候,我們需要用到一個函數 stringVar(),這個函數定義的變量會被一直追蹤,當你想要獲得該變量當時的值,只需要用該變量的 get 函數。
from tkinter import *
def b1():
print(str1.get())
root = Tk()
str1 = StringVar()
str1.set("Hello world")
Entry(root,textvariable = str1).place(x=0,y=5)
Button(root,text = "輸出",command=b1).place(x=150,y=0)
root.mainloop()
效果如下:
Tkinter 常用幾何管理方法使用介紹
上面介紹了一些組件,下面再爲大家介紹一下Tkinter
的一些幾何管理方法。所謂的幾何管理方法
就是用來組織和管理整個父配件區中子配件的佈局的。
正是有這些幾何方法的存在,我們纔可以隨心所欲的,將組件安排在我們想讓它出現的地方,所有的 Tkinter 組件都包含專用的幾何管理方法。
1. pack()
pack
幾何管理,採用塊的方式組織配件,常用在開發簡單的界面。pack 幾何管理程序根據組件創建生成的順序,將組件添加到父組件中去。如果不指定任何選項,默認在父窗體中自頂向下添加組件。
from tkinter import *
root = Tk()
Button(root,text='1',width=5).pack()
Button(root,text='2',width=5).pack()
Button(root,text='3',width=5).pack(side="left")
Button(root,text='4',width=5).pack(side = "right")
Button(root,text='5',width=5).pack(side = "bottom")
Button(root,text='6',width=5).pack()
root.mainloop()
效果如下:
2. grid()
grid
幾何管理,採用表格結構組織配件,通過行 (row) 列(column)來確定組件擺放的位置,這也是它的兩個重要的參數。
from tkinter import *
root = Tk()
Button(root,text='1',width=5).grid(row=0,column=0)
Button(root,text='2',width=5).grid(row=0,column=1)
Button(root,text='3',width=5).grid(row=0,column=2)
Button(root,text='4',width=5).grid(row=1,column=0)
Button(root,text='5',width=5).grid(row=1,column=1)
Button(root,text='6',width=5).grid(row=2,column=0)
root.mainloop()
效果如下:
3. place()
place
幾何管理,允許指定組件的大小以及位置,通過 x 和 y 的數值來確定組件的位置,通過 width 和 height 來確定組件的大小。
from tkinter import *
root = Tk()
Button(root,text='1',width=5).place(x=80,y=0)
Button(root,text='2',width=5).place(x=80,y=170)
Button(root,text='3',width=5).place(x=0,y=85)
Button(root,text='4',width=5).place(x=155,y=85)
Button(root,text='5',width=5).place(x=70,y=70,width=60,height=60)
root.mainloop()
效果如下:
Tkinter 實現彈窗提示
有時候,我們想要實現一個彈窗提示
功能。此時,可以使用 tkinter.messagebox,這個也是 Python 自帶的。在我們需要實現彈窗功能的時候,只需要將其導入,使用對應的函數,再輸入對應的參數,一個小彈窗就做好了。
from tkinter import *
import tkinter.messagebox
def b1():
tkinter.messagebox.showinfo(title="危險", message="出錯了")
root = Tk()
Button(root,text='1',command =b1 ).pack()
root.mainloop()
效果如下:
Tkinter 案例講解
通過上述對Tkinter
的講解,我們基本可以上手製作一個屬於自己的界面窗口了。最後,還是通過一個案例講解,爲大家講述它的使用。
需求: 我寫了一段自動化整理文件夾
的窗口,但是想要製作一個界面,能夠隨意選擇路徑,當我點擊桌面一鍵整理
後,就可以完成文件夾的自動整理。
下面是最後製作的界面效果,基本功能都實現了,同時還多出了兩個功能,複製所有文件名
和時間提示
,是不是很棒?
關於自動化整理文件夾
的程序,黃同學已經給出了。我在他的基礎上,結合Tkinter
,最終制作出了這個界面。完整代碼如下:
from tkinter.filedialog import askdirectory
from tkinter import *
import time
import datetime
import os
import shutil
import pyperclip
import tkinter.messagebox
class MY_GUI():
def __init__(self,init_window_name):
self.init_window_name = init_window_name
self.path = StringVar()
def selectPath(self): #選擇路徑
path_ = askdirectory()
self.path.set(path_)
def error(self): #錯誤彈窗
tkinter.messagebox.showinfo(title="提示", message="未選擇路徑")
def uptime(self): #更新時間
TimeLabel["text"] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:') + "%d" % (datetime.datetime.now().microsecond // 100000)
self.init_window_name.after(100, self.uptime)
#設置窗口
def set_init_window(self):
self.init_window_name.title("數據分析與統計學之美") #窗口標題欄
self.init_window_name.geometry('300x300+600+300') #窗口大小,300x300是窗口的大小,+600是距離左邊距的距離,+300是距離上邊距的距離
self.init_window_name.resizable(width=FALSE, height=FALSE) #限制窗口大小,拒絕用戶調整邊框大小
Label(self.init_window_name, text="歡迎使用一鍵整理小工具",bg="SkyBlue",fg = "Gray").place(x=80,y=10) #標籤組件,用來顯示內容,place裏的x、y是標籤組件放置的位置
Label(self.init_window_name, text="當前路徑:",bg="SkyBlue").place(x=15,y=50) #標籤組件,用來顯示內容,place裏的x、y是標籤組件放置的位置
Entry(self.init_window_name, textvariable=self.path).place(x=75,y=50) #輸入控件,用於顯示簡單的文本內容
Button(self.init_window_name, text="路徑選擇", command=self.selectPath,bg="SkyBlue").place(x=225,y=45) #按鈕組件,用來觸發某個功能或函數
Button(self.init_window_name, text="桌面一鍵整理",bg="SkyBlue",command=self.option).place(width=200,height=50,x=50,y=100) #按鈕組件,用來觸發某個功能或函數
Button(self.init_window_name, text="複製所有文件名",bg="SkyBlue", command=self.option1).place(width=200, height=50, x=50, y=180) #按鈕組件,用來觸發某個功能或函數
self.init_window_name["bg"] = "SkyBlue" #窗口背景色
self.init_window_name.attributes("-alpha",0.8) #虛化,值越小虛化程度越高
global TimeLabel #全局變量
TimeLabel = Label(text="%s%d" % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:'), datetime.datetime.now().microsecond // 100000),bg="SkyBlue") #標籤組件,顯示時間
TimeLabel.place(x=80, y=260)
self.init_window_name.after(100,self.uptime)
def arrangement(self,str1): #整理文件
file_dict = {
'圖片': ['jpg', 'png', 'gif', 'webp'],
'視頻': ['rmvb', 'mp4', 'avi', 'mkv', 'flv'],
"音頻": ['cd', 'wave', 'aiff', 'mpeg', 'mp3', 'mpeg-4'],
'文檔': ['xls', 'xlsx', 'csv', 'doc', 'docx', 'ppt', 'pptx', 'pdf', 'txt'],
'壓縮文件': ['7z', 'ace', 'bz', 'jar', 'rar', 'tar', 'zip', 'gz'],
'常用格式': ['json', 'xml', 'md', 'ximd'],
'程序腳本': ['py', 'java', 'html', 'sql', 'r', 'css', 'cpp', 'c', 'sas', 'js', 'go'],
'可執行程序': ['exe', 'bat', 'lnk', 'sys', 'com'],
'字體文件': ['eot', 'otf', 'fon', 'font', 'ttf', 'ttc', 'woff', 'woff2']
}
os.chdir(str1)
folder = os.listdir('.')
for each in folder:
#print(each.split('.')[-1])
for name,type in file_dict.items():
if each.split('.')[-1] in type:
if not os.path.exists(name):
os.mkdir(name)
shutil.move(each,name)
tkinter.messagebox.showinfo(title="提示", message="整理完成")
def copy(self,str1):
os.chdir(str1)
folder = os.listdir('.')
str1 = ''
for each in folder:
type = '.' + each.split('.')[-1]
str1 = str1 + each.replace(type,'') + '\n'
pyperclip.copy(str1)
#獲取當前時間
def get_current_time(self):
current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
return current_time
def option(self):
if self.path.get() == "":
self.error()
else:
self.arrangement(self.path.get())
def option1(self):
if self.path.get() == "":
self.error()
else:
self.copy(self.path.get())
if __name__ == '__main__':
init_window = Tk() # 實例化出一個父窗口
ZMJ_PORTAL = MY_GUI(init_window)
ZMJ_PORTAL.set_init_window()
init_window.mainloop()
從代碼裏可以看到,爲了窗口的整體美觀,我們規定了窗口的大小。
#窗口大小,300x300是窗口的大小,+600是距離左邊距的距離,+300是距離上邊距的距離
self.init_window_name.geometry('300x300+600+300')
還設置了窗口的基本屬性。
#窗口標題欄
self.init_window_name.title("數據分析與統計學之美")
#限制窗口大小,拒絕用戶調整邊框大小
self.init_window_name.resizable(width=FALSE, height=FALSE)
#虛化,值越小虛化程度越高
self.init_window_name.attributes("-alpha",0.8)
#窗口背景色
self.init_window_name["bg"] = "SkyBlue"
所有組件都用了 place 幾何方法,將組件的大小及佈局,進行了良好的規劃。同時,Button 組件也都與其對應的功能函數,進行了鏈接。
#標籤組件,用來顯示內容,place裏的x、y是標籤組件放置的位置
Label(self.init_window_name, text="歡迎使用一鍵整理小工具",bg="SkyBlue",fg = "Gray").place(x=80,y=10)
#標籤組件,用來顯示內容,place裏的x、y是標籤組件放置的位置
Label(self.init_window_name, text="當前路徑:",bg="SkyBlue").place(x=15,y=50)
#輸入控件,用於顯示簡單的文本內容
Entry(self.init_window_name, textvariable=self.path).place(x=75,y=50)
#按鈕組件,用來觸發某個功能或函數
Button(self.init_window_name, text="路徑選擇",command=self.selectPath,bg="SkyBlue").place(x=225,y=45)
#按鈕組件,用來觸發某個功能或函數
Button(self.init_window_name, text="桌面一鍵整理",bg="SkyBlue",command=self.option).place(width=200,height=50,x=50,y=100)
#按鈕組件,用來觸發某個功能或函數
Button(self.init_window_name, text="複製所有文件名",bg="SkyBlue", command=self.option1).place(width=200, height=50, x=50, y=180)
如果路徑爲空的時候,需要製作一個彈窗提示:未選擇路徑。
def option(self):
if self.path.get() == "":
self.error()
else:
self.arrangement(self.path.get())
def error(self): #錯誤彈窗
tkinter.messagebox.showinfo(title="提示", message="未選擇路徑")
程序打包與代碼獲取
程序打包我採用的是 pyinstaller 命令,在使用該命令前,最重要的當然就是安裝啦!
#安裝
pip install pyinstaller
#打包指令
pyinstaller -F 數據分析與統計學之美.py
在命令終端輸入安裝命令,下載安裝 pyinstaller。下載完成後再切換到存放. py 文件的目錄裏,運行打包指令,待運行結束,我們可以看到目錄裏多出了一些文件夾和文件。
下方公衆號回覆「tkinter」,即可獲取相關代碼文件。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/V_B8eQI9TvNmcB73sdin-A