简体   繁体   中英

Create label in tkinter and update the Label with an int variable

I want to create a label and update it with the int-value, which is updated by pressing the buttons, also in the label. I'm still new to Python and would like some help :)

import tkinter as tk

class Main(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.integer = tk.IntVar()
        self.integer.set(0)

        tk.Button(self, text='Quit', command=self.destroy).pack()
        tk.Button(self, text='+', command=self.plus_one).pack()
        tk.Button(self, text='-', command=self.take_one).pack()

        self.entry0 = tk.Entry(self, textvariable=str(self.integer), justify="center", width=4)
        self.entry0.pack()

    def plus_one(self):
        x =  self.integer.get() + 1
        self.integer.set(x)

    def take_one(self):
        x =  self.integer.get() - 1
        self.integer.set(x)

app = Main()
app.mainloop()

You would do this the same way you did with the Entry widget:

import tkinter as tk

class Main(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.integer = tk.IntVar()
        self.integer.set(0)

        tk.Button(self, text='Quit', command=self.destroy).pack()
        tk.Button(self, text='+', command=self.plus_one).pack()
        tk.Button(self, text='-', command=self.take_one).pack()

        self.entry0 = tk.Entry(self, textvariable=str(self.integer), justify="center", width=4)
        self.entry0.pack()

        self.label0 = tk.Label(self, textvariable=str(self.integer))
        self.label0.pack()

    def plus_one(self):
        x =  self.integer.get() + 1
        self.integer.set(x)

    def take_one(self):
        x =  self.integer.get() - 1
        self.integer.set(x)

app = Main()
app.mainloop()

As per your comments, if you are interested in having the binding at button press instead of button release, this has been already addressed here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM