Tkinter 7 Button

本文详细介绍了如何在Tkinter中使用ttk.Button组件,包括设置文本、绑定点击事件、控制button状态(正常/禁用)以及结合图片和文本的布局。还展示了下载图标按钮的创建和事件处理示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值