在本文中,您将了解 tkinter Button 小部件以及如何使用它来创建各种按钮。
Button 小部件用于显示可点击的按钮,可以将它们配置为在单击它们时调用类的函数或方法。
要创建按钮,请按如下方式使用构造函数:
button = tk.Button(master, **option)
按钮有很多选项,command 参数指定一个回调函数,该函数将在单击按钮时自动调用。
Tkinter 按钮示例import tkinter as tkroot = tk.Tk()root.geometry('300x200+200+200')root.title('Button 按钮演示')# 此处设置按钮def callback(): passbutton = tk.Button( root, text="按钮演示", command=callback)button.pack(ipadx=5, ipady=5, expand=True)root.mainloop()
也可以直接调用部分命令,不使用自定义函数。
import tkinter as tkroot = tk.Tk()root.geometry('300x200+200+200')root.title('Button 按钮演示')# 此处设置按钮button = tk.Button( root, text="退出", command=root.destroy)button.pack(ipadx=5, ipady=5, expand=True)root.mainloop()Tkinter 图像按钮示例可以在按钮上显示一个图片。
import tkinter as tkroot = tk.Tk()root.geometry('300x200+200+200')root.title('Button 按钮演示')# 此处设置按钮download_icon = tk.PhotoImage(file='Exit.png')button = tk.Button( root, image=download_icon, text="退出", command=root.destroy)button.pack(ipadx=5, ipady=5, expand=True)root.mainloop()
如果同时显示图片和文字,可以添加参数:compound。
import tkinter as tkroot = tk.Tk()root.geometry('300x200+200+200')root.title('Button 按钮演示')# 此处设置按钮download_icon = tk.PhotoImage(file='Exit.png')button = tk.Button( root, image=download_icon, text="退出", command=root.destroy, compound=tk.TOP, font=("Arial", 20))button.pack(ipadx=5, ipady=5, expand=True)root.mainloop()