today I am studying tkinter and meet something strange, can anyone help?
Here is my first code:
from tkinter import *
def click_me():
count = 1
print(f'You press {count} times button!')
root = Tk()
count = 0
Button(root, text='click me', command=click_me).pack()
root.mainloop()
I run this code get info:
local variable 'count' referenced before assignment
I can understand it because when I learn python, they told me I need use global
or click_me(count)
to do this job.
Here is my second code:
from tkinter import *
def select():
print(f'Checkbutton value is {str(var.get())}')
root = Tk()
var = IntVar() # return bool value into 1 or 0.
Checkbutton(root, text='click me', variable=var, command=select).pack()
root.mainloop()
I can run second code without any error. So I think count
and var
both are variable, the differece are one is regular variable and another are tkinker varialbe, is that reason?
CodePudding user response:
In Python, by default, you can only assign to variables in the innermost scope. When you do count = 1
(which is pretty much same as count = count 1
) you assign to count
, so Python treats it as a local variable. Because of that, when you try to calculate value of count 1
you get UnboundLocalError
.
Consider the following:
from tkinter import *
def click_me():
print(f'You press {count 1} times button!')
root = Tk()
count = 0
Button(root, text='click me', command=click_me).pack()
root.mainloop()
This code works, because you only access the value of count, and do not assign to it inside the function. So, when it is not found in the local scope, Python searches for it in the enclosing scopes.
Now, to the example with var
from tkinter import *
def select():
print(f'Checkbutton value is {str(var.get())}')
root = Tk()
var = IntVar() # return bool value into 1 or 0.
Checkbutton(root, text='click me', variable=var, command=select).pack()
root.mainloop()
Here, you also do not assign to var, so it does not get marked as local. Now, let's add seemingly pointless line of code: var = var
def select():
var = var
print(f'Checkbutton value is {str(var.get())}')
This gives us exactly same error as with count
- because of assignment to var
, it is treated as a local variable and thus you get an error when trying to access its value.