Tkinter 窗口和按钮
带有 onClick
事件的 Tk 按钮
要使用按钮创建 Tkinter 窗口,请使用下面的示例。程序进入 mainloop()
,等待事件(用户操作)。我们定义了一个回调函数 callback()
的按钮。master 是根窗口,即按钮出现的窗口。
from Tkinter import *
master = Tk()
def callback():
print "click!"
b = Button(master, text="OK", command=callback)
b.pack()
mainloop()

Tk 图像按钮
如果需要图像按钮,请使用 PhotoImage 类。我们使用函数 minsize()
和 geometry()
设置窗口的大小和 miminum 大小。例:
from Tkinter import *
master = Tk()
master.minsize(300,100)
master.geometry("320x100")
def callback():
print "click!"
photo=PhotoImage(file="add.png")
b = Button(master,image=photo, command=callback, height=50, width=150)
b.pack()
mainloop()
结果:

带文本标签的 Tk 图像按钮
如果要同时显示图像和文本,只需添加参数 compound = LEFT 即可。
from Tkinter import *
master = Tk()
master.minsize(300,100)
master.geometry("320x100")
def callback():
print "click!"
photo=PhotoImage(file="add.png")
b = Button(master,image=photo, text="OK", command=callback, height=50, width=150, compound=LEFT)
b.pack()
mainloop()
结果:

按钮位置
如果要将按钮放在坐标上,请不要使用 pack()
函数,而是使用函数 place(x, y)
,如下例所示:
from Tkinter import *
master = Tk()
master.minsize(300,100)
master.geometry("320x100")
def callback():
print "click!"
photo=PhotoImage(file="add.png")
b = Button(master,image=photo, text="OK", command=callback, height=50, width=150, compound=LEFT)
b.place(x = 20, y = 20)
mainloop()
结果:
