在按下时创建一个按钮 在 python 3.3 的输入框中打印该按钮上的数字

编程入门 行业动态 更新时间:2024-10-23 21:34:45
本文介绍了在按下时创建一个按钮 在 python 3.3 的输入框中打印该按钮上的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-30 08:08:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391363.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   按下   创建一个   框中   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!