Update a label in Tkinter when pressing a button

前端 未结 3 856
野的像风
野的像风 2021-01-24 04:34

I want to make a \"program\" that updates a label when you press a button and print out a variable, but with the code i have it does not work. Can someone help me out?

T

3条回答
  •  没有蜡笔的小新
    2021-01-24 04:45

    An alternative solution: using the textvariable tag along with a Tkinter IntVar.

    Example:

    from Tkinter import *
    
    root = Tk()
    x = IntVar()
    
    
    def test():
        global x
        x.set(x.get() + 1)
    
    label_1 = Label(root, text=x.get(), textvariable = x)
    button_1 = Button(root, text='Click', command=test)
    button_1.grid(row=0, column=0)
    label_1.grid(row=0, column=1)
    
    root.mainloop()
    

    *EDIT: Removed the label_1.update() call as it is unnecessary

提交回复
热议问题