jon
jon

Reputation: 359

How to use a variable inside of a function without declaring it as a global variable

I have a 2 part question (if that's not allowed, I really only need to first part answered)

I have the following sample code

import tkinter as tk

window = tk.Tk()

def countIncrease():
    count +=1
    t1.insert(tk.END,count)

count = 0
t1=tk.Text(window,height=3,width=30)
t1.grid(row=0,column=0,columnspan=3)

b1=tk.Button(window,text="+",height=3,width=10,command=countIncrease)
b1.grid(row=1,column=0)

window.mainloop()

and if I execute this code, I get the error UnboundLocalError: local variable 'count' referenced before assignment

I know that I could simply fix this by adding global count to the function

After I do that, when I press the button, the output is 1, and repeated presses produce 12, 123, 1234, 12345 and so on.

My first (and main) question is that I know it is bad practice to make variables global. What would be the proper way of making this work without making count a global variable?

My second question is how do I make the screen "refresh" so it is only showing the up to date variable, ie instead of 123 its just 3.

Upvotes: 0

Views: 56

Answers (1)

Khristos
Khristos

Reputation: 983

You should restructure your code to use a class and make count a class variable if you don't want to use a global variable. And to 'refresh' the screen/tkinter text, you need to delete the content before inserting new one.

Here is one way you can address the two issues:

import tkinter as tk

class app():
    def __init__(self, parent):
        self.count = 0
        self.t1=tk.Text(parent, height=3,width=30)
        self.t1.grid(row=0,column=0,columnspan=3)

        self.b1=tk.Button(parent,text="+",height=3,width=10,command=self.countIncrease)
        self.b1.grid(row=1,column=0)

    def countIncrease(self):
        self.count +=1
        self.t1.delete('1.0', tk.END) #refresh/delete content of t1
        self.t1.insert(tk.END,self.count)

window = tk.Tk()
app(window) # Create an instance of app
window.mainloop()

Upvotes: 1

Related Questions