为什么我的”abc“内容直接就出来了,我还没点button呢?fun()不应该是点了之后才被调用的command吗?
from tkinter import *
root=Tk()
txt=Text(root)
def fun():
txt.insert(END,"abc")
b=Button(root,text="hit",command=fun())
txt.pack()
b.pack()
root.mainloop()
在你的代码中,fun()
函数被立即调用,而不是等到按钮被点击后才调用。这是因为你在command
参数中直接传递了函数调用的结果(fun()
),而不是函数本身(fun
)。
在Python中,函数是一等公民,可以将函数作为参数传递给其他函数或对象。在Tkinter中,按钮的command
参数接收一个回调函数,这个函数将在按钮被点击时执行。
要解决这个问题,你只需要将command
参数更改为command=fun
,而不是command=fun()
。这样,Tkinter会将函数引用传递给按钮,而不是立即调用函数。以下是修正后的代码:
from tkinter import *
root = Tk()
txt = Text(root)
def fun():
txt.insert(END, "abc")
b = Button(root, text="hit", command=fun) # 去掉函数调用的括号
txt.pack()
b.pack()
root.mainloop()
现在,当你点击按钮时,fun()
函数将被调用,并在文本框中插入"abc"。
【以下回答由 GPT 生成】
问题分析: 问题出现在点击按钮时,函数fun()被立即调用,而不是在点击按钮后被调用。这是因为在创建按钮时,将command
参数设置为fun()
,这会导致函数被立即调用并返回其结果,而不是等待按钮点击后才调用函数。正确的做法应该是将command
参数设置为fun
,即将函数本身传递给command
参数。
解决方案: 修改代码中的按钮创建部分如下:
b = Button(root, text="点击", command=fun)
这样修改后,函数fun()将在按钮被点击时调用,而不是在按钮创建时被立即调用。这样就能实现在点击按钮后将"abc"内容插入到文本框中的效果。修改后的完整代码如下:
from tkinter import *
root = Tk()
txt = Text(root)
def fun():
txt.insert(END, "abc")
b = Button(root, text="点击", command=fun)
txt.pack()
b.pack()
root.mainloop()
这样就可以实现在点击按钮后"abc"内容才出现在文本框中的效果。