问题描述
限时送ChatGPT账号..我想做一个按钮,上面写着2"....现在当有人点击它时,它会在输入框中显示数字2"...错误是:在点击之前,它已经在输入框中显示2"
i want to make a button on which '2' is written .... now when anyone click it , it will show the number '2' in the entry box... the error is: before clicking , it is already showing '2' in the entry box
所以请帮我消除这个错误这是我的程序
So please help me removing this error here is my program
from tkinter import *
root = Tk()
def add(x):
e1=Entry(root)
e1.insert(INSERT, x)
e1.pack()
a=Button(root, text='2', command=add(2))
a.pack()
root.mainloop()
推荐答案
传递一个函数(在下面的代码中使用了lambda
)而不是函数的返回值.
Pass a function (used lambda
in the following code) instead of return value of the function.
from tkinter import *
root = Tk()
e1 = Entry(root)
e1.pack()
def add(x):
e1.insert(INSERT, x)
a = Button(root, text='2', command=lambda: add(2))
a.pack()
root.mainloop()
除此之外,从 add
函数中提取 Entry 创建代码.否则每次点击按钮时都会创建条目.
In addition to that, extract Entry creation code out of the add
function. Otherwise entry are create every time when the button is clicked.
这篇关于在按下时创建一个按钮 在 python 3.3 的输入框中打印该按钮上的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论