在本文中,您將了解 tkinter Button 小部件以及如何使用它來(lái)創(chuàng)建各種按鈕。
Button 小部件用于顯示可點(diǎn)擊的按鈕,可以將它們配置為在單擊它們時(shí)調(diào)用類的函數(shù)或方法。
要?jiǎng)?chuàng)建按鈕,請(qǐng)按如下方式使用構(gòu)造函數(shù):
button = tk.Button(master, **option)
按鈕有很多選項(xiàng),command 參數(shù)指定一個(gè)回調(diào)函數(shù),該函數(shù)將在單擊按鈕時(shí)自動(dòng)調(diào)用。
Tkinter 按鈕示例
import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按鈕演示')
# 此處設(shè)置按鈕
def callback():
pass
button = tk.Button(
root,
text="按鈕演示",
command=callback
)
button.pack(ipadx=5, ipady=5, expand=True)
root.mainloop()
也可以直接調(diào)用部分命令,不使用自定義函數(shù)。
import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按鈕演示')
# 此處設(shè)置按鈕
button = tk.Button(
root,
text="退出",
command=root.destroy
)
button.pack(ipadx=5, ipady=5, expand=True)
root.mainloop()
Tkinter 圖像按鈕示例
可以在按鈕上顯示一個(gè)圖片。
import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按鈕演示')
# 此處設(shè)置按鈕
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()
如果同時(shí)顯示圖片和文字,可以添加參數(shù):compound。
import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按鈕演示')
# 此處設(shè)置按鈕
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()
Tkinter 按鈕其他選項(xiàng)
import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按鈕演示')
def callback():
pass
# 此處設(shè)置按鈕
button = tk.Button(
root,
text="Click Me",
command=callback,
activebackground="blue", # 按鈕按下時(shí)的顏色
activeforeground="white", # 按鈕按下時(shí)文字顏色
bd=1, # 按鈕邊框?qū)挾?/span>
bg="lightgray", # 按鈕背景色
cursor="hand2", # 鼠標(biāo)指針樣式
fg="black", # 文字顏色
font=("Arial", 12), # 文字字體字號(hào)
height=2, # 按鈕高度
justify="center", # 對(duì)齊方式
padx=10, # 文字左右邊距
pady=5, # 文字上下邊距
width=15, # 按鈕寬度
wraplength=100 # 文本換行
)
button.pack(ipadx=5, ipady=5, expand=True)
root.mainloop()