You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter入门问题:按钮command点击未触发,窗口加载直接执行逻辑

问题根因
  • Button的command参数需要传入函数对象,你写的click()带了括号,程序初始化时会直接执行该函数,所以窗口刚打开就显示了标签。
修复方法

将command = click()修改为command = click,去掉括号直接传入函数名即可实现点击触发的效果。

修正后可运行代码
from tkinter import *

root = Tk()

def click():
    label = Label(root, text = 'clicked!')
    label.pack()

button = Button(root, text='click me', command = click)

button.pack()

root.mainloop()
可选优化

如果需要避免多次点击重复生成多个标签,可以提前创建标签并隐藏,点击时再修改显示状态:

from tkinter import *

root = Tk()

# 提前创建标签,默认不显示
label = Label(root, text = 'clicked!')

def click():
    label.pack()

button = Button(root, text='click me', command = click)
button.pack()

root.mainloop()

内容的提问来源于stack exchange,提问作者anji suri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 10:24:03