Update a label in Tkinter when pressing a button

前端 未结 3 823
野的像风
野的像风 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:34

    If you want to write it as a class, which has numerous advantages...

    import Tkinter as tk
    
    class Application(tk.Frame):
        def __init__(self, master=None):
            self.x = tk.IntVar()
    
            tk.Frame.__init__(self, master)
            self.pack()
            self.createWidgets()
    
        def createWidgets(self):
            tk.Label(self, textvariable=self.x).pack()
            tk.Button(self, text='Click', command=self.increment).pack()
    
        def increment(self):
            self.x.set(self.x.get() + 1)
    
    root = tk.Tk()
    app = Application(master=root)
    app.mainloop()
    
    0 讨论(0)
  • 2021-01-24 04:44

    Instead of label_1.update() (which doesn't do anything close to what you think it does), reconfigure the widget with label_1.config(text=x).

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题