为什么两个标签都没有更新?

时间:2015-02-13 13:15:59

标签: python tkinter

import Tkinter

class Store1:
    def __init__(self):
        self.variable = Tkinter.IntVar()
        self.variable1 = Tkinter.IntVar()

    def add(self):
        counter1 = self.variable
        counter1.set(counter1.get() + 1)
        counter2 = self.variable1
        counter2.set(counter2.get() + 1)
        return counter1.get(), counter2.get()

class Main(Tkinter.Tk):
    def __init__(self, *args, **kwargs):
        Tkinter.Tk.__init__(self, *args, **kwargs)
        counter1 = Store1()
        counter2 = Store1()


        self.label  = Tkinter.Label(self, textvariable=counter1.variable)
        self.button = Tkinter.Button(self, command=lambda:counter1.add(), text='+1')
        self.label.pack()
        self.button.pack()

        self.label1  = Tkinter.Label(self, textvariable=counter2.variable1)
        self.button1 = Tkinter.Button(self, command=lambda:counter2.add(), text='+1')
        self.label1.pack()
        self.button1.pack()




root = Main()
root.mainloop()

1 个答案:

答案 0 :(得分:0)

定义一个调用两个要添加的计数器的函数。

import Tkinter

class Store1:
    def __init__(self):
        self.variable = Tkinter.IntVar()
        self.variable1 = Tkinter.IntVar()

    def add(self):
        counter1 = self.variable
        counter1.set(counter1.get() + 1)
        counter2 = self.variable1
        counter2.set(counter2.get() + 1)
        return counter1.get(), counter2.get()

class Main(Tkinter.Tk):
    def __init__(self, *args, **kwargs):
        Tkinter.Tk.__init__(self, *args, **kwargs)
        counter1 = Store1()
        counter2 = Store1()

        def both_counters():
            counter1.add()
            counter2.add()

        self.label  = Tkinter.Label(self, textvariable=counter1.variable)
        self.button = Tkinter.Button(self, command=both_counters, text='+1')
        self.label.pack()
        self.button.pack()

        self.label1  = Tkinter.Label(self, textvariable=counter2.variable1)
        self.button1 = Tkinter.Button(self, command=both_counters, text='+1')
        self.label1.pack()
        self.button1.pack()

root = Main()
root.mainloop()