在标签上显示变量Tkinter python 2.7

时间:2015-03-28 19:19:54

标签: python-2.7 tkinter

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

我正在使用gui处理一个小程序,按下一个按钮,它为变量加1,按第二个按钮,减去,按第三个按钮,它打印变量的当前值。现在我希望它始终在gui上打印变量,在标签上,我已经阅读了如何做到这一点,我想我得到了它,但是当我去运行代码时,标签不起作用。它运行,所以没有错误消息。

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()

1 个答案:

答案 0 :(得分:2)

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

因此,使用IntVar初始化学生并调整增量代码应该可以胜任。

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

#(...)
students = IntVar()