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()


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