1.使用Tkinter创建图形用户界面的步骤
(1)导入Tkinter模块,使用import Tkinter或from Tkinter import *
(2)创建顶层窗口对象容器,使用top = Tkinter.Tk()
(3)在顶层窗口对象上创建GUI对象
(4)将GUI对象与底层程序代码相连接
(5)进入主事件循环
例如:
# !/usr/bin/env python import Tkinter top = Tkinter.Tk() label = Tkinter.Label(top, text="Hello, World") label.pack() Tkinter.mainloop()
# !/usr/bin/env python import Tkinter top = Tkinter.Tk() hello_label = Tkinter.Label(top, text="Hello, World") hello_label.pack() quit_button = Tkinter.Button(top, text="Quit", command=top.quit, bg="pink", fg="blue") quit_button.pack(fill=Tkinter.X, expand=1) Tkinter.mainloop()
例如:通过进度条改变文字的大小
# !/usr/bin/env python #第一步:导入Tkinter类 import Tkinter def resize(ev=None): '''通过进度条改变文字的大小''' hello_label.config(font="Helvetica -%d bold" % hello_scale.get()) #第二部:创建顶层窗口容器对象 top = Tkinter.Tk() top.geometry("250x150") #第三步:创建GUI对象 hello_label = Tkinter.Label(top, text="Hello, World", font="Helvetica -12 bold") #第四步:将GUI对象与顶层代码连接 hello_label.pack(fill=Tkinter.Y, expand=1) hello_scale = Tkinter.Scale(top, from_=10, to=40, orient=Tkinter.HORIZONTAL, command=resize) hello_scale.set(12) hello_scale.pack(fill=Tkinter.X, expand=1) quit_button = Tkinter.Button(top, text="Quit", command=top.quit, activeforeground="white", activebackground="red") quit_button.pack() #第五步:进入主事件循环 Tkinter.mainloop()
例如:偏函数的使用
#!/usr/bin/env python # -*- coding: UTF-8 -*- from functools import partial import Tkinter top = Tkinter.Tk() top.title("Button") MyButton = partial(Tkinter.Button, top, bg="blue", fg="white") button1 = MyButton(text="Button1") button1.pack() button2 = MyButton(text="Button2") button2.pack() button3 = MyButton(text="Quit", command=top.quit) button3.pack(fill=Tkinter.X, expand=2) Tkinter.mainloop()