mr. bug
mr. bug

Reputation: 309

How to stop an integer from resetting to its original value after each button press in tkinter

I am making a program so that when the user presses any of the buttons the total_votes value increases by one. How do I make the total_votes value not reset back to 15 whenever I repress the button?

import tkinter as tk

total_votes = 15

root = tk.Tk()


class VoteButton:
    def __init__(self, row, column, text):
        self.row = row
        self.column = column
        self.text = text
        self.vbtn = tk.Button(root, text=self.text, command=lambda: self.voting(total_votes))

    def draw(self):
        self.vbtn.grid(row=self.row, column=self.column)

    def voting(self, tv):
        tv += 1
        print(tv)


btn = VoteButton(0, 0, "button")
btn.draw()

btn2 = VoteButton(0, 1, "button")
btn2.draw()

root.mainloop()

Upvotes: 0

Views: 73

Answers (2)

acw1668
acw1668

Reputation: 46669

Changing argument tv inside voting() does not change the global variable total_votes because only the value of total_votes is passed via the argument tv (passed by value) by the line self.voting(total_votes).

To change the global variable total_votes, you need to update it directly inside voting() and declaring it as global variable inside the function via global total_votes:

class VoteButton:
    def __init__(self, row, column, text):
        self.row = row
        self.column = column
        self.text = text
        self.vbtn = tk.Button(root, text=self.text, command=self.voting)

    ...

    def voting(self):
        global total_votes
        total_votes += 1
        print(total_votes)

However I would suggest to change total_votes to class variable of VoteButton to avoid using global variable:

class VoteButton:
    total_votes = 15   # class variable

    def __init__(self, row, column, text):
        self.row = row
        self.column = column
        self.text = text
        self.vbtn = tk.Button(root, text=self.text, command=self.voting)

    ...

    def voting(self):
        VoteButton.total_votes += 1
        print(VoteButton.total_votes)

Upvotes: 2

ApplesAndCode464
ApplesAndCode464

Reputation: 76

total_votes isn't redefined to be tv in the voting function. You can fix your problem by changing the voting function, like this:

def voting(self, tv):
    tv += 1
    total_votes = tv
    print(tv)

Upvotes: 1

Related Questions