to create a button when pressed print the number on that button in the entry box in python 3.3

后端 未结 2 1202
囚心锁ツ
囚心锁ツ 2020-12-20 07:30

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 a

相关标签:
2条回答
  • 2020-12-20 07:49

    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()
    

    In addition to that, extract Entry creation code out of the add function. Otherwise entry are create every time when the button is clicked.

    0 讨论(0)
  • 2020-12-20 07:51

    When you do:

    a=Button(root, text='2', command=add(2))  
    

    it is the same as:

    add(2)
    a=Button(root, text='2', command=None)  
    

    i.e. you are calling add and assigning its return value to command. Instead, you can use functools.partial to create a function that will call add with the argument 2:

    from functools import partial
    
    a=Button(root, text='2', command=partial(add, 2))
    
    0 讨论(0)
提交回复
热议问题