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

Tkinter按钮组件未点击却自动执行代码问题求助

问题解决:Tkinter按钮未点击就执行绑定函数

你的代码核心错误在于Button组件的command参数设置:

  • 你写的是command=Click(),这会在创建Button时立即调用Click函数,而不是把函数绑定到按钮的点击事件上。

修正方法

把command=Click()改成command=Click(去掉函数名后的括号),这样传入的是函数对象,Tkinter会在按钮被点击时才执行这个函数。

另外,Click函数里的Label1.grid(column=2, row=1)可以省略,因为标签已经完成布局,修改文本不需要重复调用grid。

修正后的完整代码

from tkinter import *

Window = Tk()
Window.title("Button on Click")
Window.geometry("350x350")

Label1 = Label(Window, text="Click the button")
Label1.grid(column=2, row=1)

def Click():
   Label1.configure(text="You clicked the button!")

Button1 = Button(Window, text="Surprise!", fg="blue", command=Click)
Button1.grid(column=1, row=1)

Window.mainloop()

内容的提问来源于stack exchange,提问作者Adenosine Triphosphate

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 18:42:34