8000字 | 詳解 Tkinter 的 GUI 界面制作!

效果展示
Tkinter制作一個(gè)簡單的可視化界面工具。有時(shí)候,我們用代碼實(shí)現(xiàn)了某些功能,如果可以為這個(gè)功能添加一個(gè)界面,是否會(huì)感覺倍兒爽?Tkinter做出來的最終效果吧!
Tkinter簡介
Tkinter(也叫 Tk 接口)是 Tk 圖形用戶界面工具包標(biāo)準(zhǔn) 的 Python 接口。Tkinter是Python自帶的標(biāo)準(zhǔn)庫,我們想要使用它的時(shí)候,只需直接導(dǎo)入即可。from tkinter import *
Tkinter支持的組件有:
Tkinter常用組件使用介紹
Tkinter中的常用組件。各個(gè)組件有其相對(duì)應(yīng)的功能和用法,而我們可以根據(jù)我這些控件自由組合來展現(xiàn)出我們想要的效果。小工具里會(huì)用到的一些組件。1. 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(標(biāo)簽控件)
from tkinter import *
root = Tk()
str1 = "Hello World"
Label(root,text=str1).place(x=0,y=0)
root.mainloop()

3. Entry(文本框)
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的一些幾何管理方法。所謂的幾何管理方法就是用來組織和管理整個(gè)父配件區(qū)中子配件的布局的。1. pack()
pack幾何管理,采用塊的方式組織配件,常用在開發(fā)簡單的界面。pack幾何管理程序根據(jù)組件創(chuàng)建生成的順序,將組件添加到父組件中去。如果不指定任何選項(xiàng),默認(rèn)在父窗體中自頂向下添加組件。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幾何管理,采用表格結(jié)構(gòu)組織配件,通過行(row)列(column)來確定組件擺放的位置,這也是它的兩個(gè)重要的參數(shù)。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的數(shù)值來確定組件的位置,通過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實(shí)現(xiàn)彈窗提示
彈窗提示功能。此時(shí),可以使用tkinter.messagebox,這個(gè)也是Python自帶的。在我們需要實(shí)現(xiàn)彈窗功能的時(shí)候,只需要將其導(dǎo)入,使用對(duì)應(yīng)的函數(shù),再輸入對(duì)應(yīng)的參數(shù),一個(gè)小彈窗就做好了。from tkinter import *
import tkinter.messagebox
def b1():
tkinter.messagebox.showinfo(title="危險(xiǎn)", message="出錯(cuò)了")
root = Tk()
Button(root,text='1',command =b1 ).pack()
root.mainloop()

Tkinter案例講解
Tkinter的講解,我們基本可以上手制作一個(gè)屬于自己的界面窗口了。最后,還是通過一個(gè)案例講解,為大家講述它的使用。自動(dòng)化整理文件夾的窗口,但是想要制作一個(gè)界面,能夠隨意選擇路徑,當(dāng)我點(diǎn)擊桌面一鍵整理后,就可以完成文件夾的自動(dòng)整理。復(fù)制所有文件名和時(shí)間提示,是不是很棒?
自動(dòng)化整理文件夾的程序,黃同學(xué)已經(jīng)給出了。我在他的基礎(chǔ)上,結(jié)合Tkinter,最終制作出了這個(gè)界面。完整代碼如下: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): #錯(cuò)誤彈窗
tkinter.messagebox.showinfo(title="提示", message="未選擇路徑")
def uptime(self): #更新時(shí)間
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)
#設(shè)置窗口
def set_init_window(self):
self.init_window_name.title("數(shù)據(jù)分析與統(tǒng)計(jì)學(xué)之美") #窗口標(biāo)題欄
self.init_window_name.geometry('300x300+600+300') #窗口大小,300x300是窗口的大小,+600是距離左邊距的距離,+300是距離上邊距的距離
self.init_window_name.resizable(width=FALSE, height=FALSE) #限制窗口大小,拒絕用戶調(diào)整邊框大小
Label(self.init_window_name, text="歡迎使用一鍵整理小工具",bg="SkyBlue",fg = "Gray").place(x=80,y=10) #標(biāo)簽組件,用來顯示內(nèi)容,place里的x、y是標(biāo)簽組件放置的位置
Label(self.init_window_name, text="當(dāng)前路徑:",bg="SkyBlue").place(x=15,y=50) #標(biāo)簽組件,用來顯示內(nèi)容,place里的x、y是標(biāo)簽組件放置的位置
Entry(self.init_window_name, textvariable=self.path).place(x=75,y=50) #輸入控件,用于顯示簡單的文本內(nèi)容
Button(self.init_window_name, text="路徑選擇", command=self.selectPath,bg="SkyBlue").place(x=225,y=45) #按鈕組件,用來觸發(fā)某個(gè)功能或函數(shù)
Button(self.init_window_name, text="桌面一鍵整理",bg="SkyBlue",command=self.option).place(width=200,height=50,x=50,y=100) #按鈕組件,用來觸發(fā)某個(gè)功能或函數(shù)
Button(self.init_window_name, text="復(fù)制所有文件名",bg="SkyBlue", command=self.option1).place(width=200, height=50, x=50, y=180) #按鈕組件,用來觸發(fā)某個(gè)功能或函數(shù)
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") #標(biāo)簽組件,顯示時(shí)間
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'],
'可執(zhí)行程序': ['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)
#獲取當(dāng)前時(shí)間
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() # 實(shí)例化出一個(gè)父窗口
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')
#窗口標(biāo)題欄
self.init_window_name.title("數(shù)據(jù)分析與統(tǒng)計(jì)學(xué)之美")
#限制窗口大小,拒絕用戶調(diào)整邊框大小
self.init_window_name.resizable(width=FALSE, height=FALSE)
#虛化,值越小虛化程度越高
self.init_window_name.attributes("-alpha",0.8)
#窗口背景色
self.init_window_name["bg"] = "SkyBlue"
#標(biāo)簽組件,用來顯示內(nèi)容,place里的x、y是標(biāo)簽組件放置的位置
Label(self.init_window_name, text="歡迎使用一鍵整理小工具",bg="SkyBlue",fg = "Gray").place(x=80,y=10)
#標(biāo)簽組件,用來顯示內(nèi)容,place里的x、y是標(biāo)簽組件放置的位置
Label(self.init_window_name, text="當(dāng)前路徑:",bg="SkyBlue").place(x=15,y=50)
#輸入控件,用于顯示簡單的文本內(nèi)容
Entry(self.init_window_name, textvariable=self.path).place(x=75,y=50)
#按鈕組件,用來觸發(fā)某個(gè)功能或函數(shù)
Button(self.init_window_name, text="路徑選擇",command=self.selectPath,bg="SkyBlue").place(x=225,y=45)
#按鈕組件,用來觸發(fā)某個(gè)功能或函數(shù)
Button(self.init_window_name, text="桌面一鍵整理",bg="SkyBlue",command=self.option).place(width=200,height=50,x=50,y=100)
#按鈕組件,用來觸發(fā)某個(gè)功能或函數(shù)
Button(self.init_window_name, text="復(fù)制所有文件名",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): #錯(cuò)誤彈窗
tkinter.messagebox.showinfo(title="提示", message="未選擇路徑")
程序打包與代碼獲取
#安裝
pip install pyinstaller
#打包指令
pyinstaller -F 數(shù)據(jù)分析與統(tǒng)計(jì)學(xué)之美.py

推薦閱讀:
入門: 最全的零基礎(chǔ)學(xué)Python的問題 | 零基礎(chǔ)學(xué)了8個(gè)月的Python | 實(shí)戰(zhàn)項(xiàng)目 |學(xué)Python就是這條捷徑
量化: 定投基金到底能賺多少錢? | 我用Python對(duì)去年800只基金的數(shù)據(jù)分析
干貨:爬取豆瓣短評(píng),電影《后來的我們》 | 38年NBA最佳球員分析 | 從萬眾期待到口碑撲街!唐探3令人失望 | 笑看新倚天屠龍記 | 燈謎答題王 |用Python做個(gè)海量小姐姐素描圖 |碟中諜這么火,我用機(jī)器學(xué)習(xí)做個(gè)迷你推薦系統(tǒng)電影
趣味:彈球游戲 | 九宮格 | 漂亮的花 | 兩百行Python《天天酷跑》游戲!
AI: 會(huì)做詩的機(jī)器人 | 給圖片上色 | 預(yù)測收入 | 碟中諜這么火,我用機(jī)器學(xué)習(xí)做個(gè)迷你推薦系統(tǒng)電影
小工具: Pdf轉(zhuǎn)Word,輕松搞定表格和水印! | 一鍵把html網(wǎng)頁保存為pdf!| 再見PDF提取收費(fèi)! | 用90行代碼打造最強(qiáng)PDF轉(zhuǎn)換器,word、PPT、excel、markdown、html一鍵轉(zhuǎn)換 | 制作一款釘釘?shù)蛢r(jià)機(jī)票提示器! |60行代碼做了一個(gè)語音壁紙切換器天天看小姐姐!|
年度爆款文案
2).學(xué)Python真香!我用100行代碼做了個(gè)網(wǎng)站,幫人PS旅行圖片,賺個(gè)雞腿吃
9).發(fā)現(xiàn)一個(gè)舔狗福利!這個(gè)Python爬蟲神器太爽了,自動(dòng)下載妹子圖片
點(diǎn)閱讀原文,領(lǐng)AI全套資料!


