Button可以是文本,也可以是图片,是一个可点击对象
button = ttk.Button(master, **option)
最常见的button格式:
button = ttk.Button(master, text, command)
- master:主窗口
- text:按钮名称
- command:点击按钮时调用的函数
comand绑定函数的两种方法:
def callback():
# do something
ttk.Button(
root,
text="Demo Button",
command=callback
)
也可以使用lambda:
ttk.Button(
root,
text="Demo Button",
command=lambda_expression
)
button的状态:分normal(默认状态)和disable。button状态可以使用state函数设定:
# set the disabled flag
button.state(['disabled'])
# remove the disabled flag
button.state(['!disabled'])
如果在Button中,同时展示图片和文本,类似于Label,可以使用compound排列图片、文本的相对位置
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
# root window
root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Image Button Demo')
# download button handler
def download_clicked():
showinfo(
title='Information',
message='Download button clicked!'
)
download_icon = tk.PhotoImage(file='./assets/download.png')
download_button = ttk.Button(
root,
image=download_icon,
text='Download',
compound=tk.LEFT,
command=download_clicked
)
download_button.pack(
ipadx=5,
ipady=5,
expand=True
)
root.mainloop()