0

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.

1

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.