user4714953
user4714953

Reputation:

Displaying variable on a label Tkinter python 2.7

I read some similiar questions here but couldn't fix my code, so i ask.

I'm working on a little program with a gui, press a button, it adds 1 to a variable, press the second button, it subtract, press the third button, it prints the current value of the variable. Now i want it to print the variable always on the gui, on a label, i've read how to do it and i thought i got it, but when i went to run the code the label was not working. It runs though, so no error message.

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

Upvotes: 1

Views: 305

Answers (1)

FabienAndre
FabienAndre

Reputation: 4594

Label textvariable parameter expect special kind of tkinter/tcl variables. These ones can be traced, in the meaning that any piece of the program can subscribe to their value and be notified when it changes.

Thus, initializing students with an IntVar and adapting you increment code should do the job.

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

#(...)
students = IntVar()

Upvotes: 2

Related Questions