在标签 Tkinter python 2.7 上显示变量

Displaying variable on a label Tkinter python 2.7

我在这里读到一些类似的问题,但无法修复我的代码,所以我问。

我正在编写一个带有图形用户界面的小程序,按下一个按钮,它向变量加 1,按下第二个按钮,它减去,按下第三个按钮,它打印变量的当前值。现在我希望它始终在 gui 上打印变量,在标签上,我已经阅读了如何做,我以为我明白了,但是当我转到 运行 代码时,标签不起作用。不过 运行s,所以没有错误消息。

from Tkinter import *

class experiment:


    def __init__(self, master):
        global students
        frame = Frame(master)
        frame.pack()

        self.addbutton = Button(frame, text="Add Student", command=self.addstudent, bg="black", fg="white")
        self.addbutton.grid(row=0, column=1, sticky = E)

        self.subbutton = Button(frame,text="Subtract Student", command=self.subtractstudent, bg="black", fg="white")
        self.subbutton.grid(row=0, column=2, sticky = E)

        self.checkbutton = Button(frame,text="Check Record", command=self.checkstudentrec, bg="black", fg="white")
        self.checkbutton.grid(row=0, column=3, sticky= E )

        self.quitButton = Button(frame,text="Quit", command=frame.quit)
        self.quitButton.grid(row=2, column=3, sticky=W)

        self.label1 = Label(frame, textvariable = students)
        self.label1.grid(row=2, column=1)

    def addstudent(self):
        global students
        students = students + 1
        print "\n Student Added"
    def subtractstudent(self):
        global students
        students = students - 1
        print "\n Student Deleted"
    def checkstudentrec(self):
        print students
        print "\n Student Record Found"

root = Tk()
students = 0
b = experiment(root)
root.mainloop()

标签textvariable参数预期special kind of tkinter/tcl variables。这些是可以追踪的,意思是程序的任何部分都可以订阅它们的值并在它发生变化时得到通知。

因此,用 IntVar 初始化学生并调整你的增量代码应该可以完成这项工作。

def addstudent(self):
    global students
    students.set(students.get() + 1)

#(...)
students = IntVar()