Python GUI編程入門

        大多數時候,你只需要tkinter就可以了,但是還有一些額外的模塊也可以使用。 Tk接口位於名爲_tkinter的二進制模塊中。 該模塊包含Tk的低級接口,應用程序員不應該直接使用這些接口。 它通常是一個共享庫(或DLL),但在某些情況下可能會與Python解釋器靜態鏈接。

除了Tk接口模塊外,tkinter還包含許多Python模塊,tkinter.constants是最重要的一個。 導入tkinter會自動導入tkinter.constants,所以通常要使用Tkinter,你需要的只是一個簡單的import語句:

from functools import partial as pto
import tkinter as tk
import tkinter.messagebox as mb

1、最簡單的程式

#創建主窗口
top = tk.Tk()
#開始運行
top.mainloop()

2、空間與窗口的綁定

#創建主窗口
top = tk.Tk()

#創建控件的時候,第一個參數爲空間所在的窗口
#創建標籤
label = tk.Label(top, text="Hello World!")
label.pack()

#創建按鈕
quit = tk.Button(top, text="Quit", command=top.quit)
quit.pack(fill=tk.X, expand=1)

#開始運行
top.mainloop()

3、動態創建控件

# 按鈕種類的定義
WARN = "warn"
CRIT = "crit"
REGU = "regu"

SIGNS = {
"do not enter":CRIT,
"railroad crossing":WARN,
"55\nspeed limit":REGU,
"wrong way":CRIT,
"merging traffic":WARN,
"one way":REGU,
}

#按鈕回調函數的定義
critCB = lambda : mb.showerror("Error", "Error Button Pressed!")
warnCB = lambda : mb.showwarning("Warning", "Warning Button Pressed!")
infoCB = lambda : mb.showinfo("Info", "Info Button Pressed!")

#創建主窗口
top = tk.Tk()
top.title("Road Signs")

#創建退出按鈕,點擊時調用top.quit
tk.Button(top, text="QUIT", command=top.quit, bg="red", fg = "white").pack()

#創建Button模板
mybutton = pto(tk.Button, top)
CritButton = pto(mybutton, command=critCB, bg="white", fg="red")
WarnButton = pto(mybutton, command=warnCB, bg="goldenrod1")
ReguButton = pto(mybutton, command=infoCB, bg="white")

#使用上面的Button模板創建實際按鈕
for eachSign in SIGNS:
signType = SIGNS[eachSign]
cmd = '%sButton(text=%r%s).pack(fill=tk.X, expand=True)' % (signType.title(), eachSign, '.upper()' if signType == CRIT else '.title()')
print("cmd = ", cmd)
eval(cmd)

#啓動主循環,開啓主窗口
top.mainloop()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章