0
whats wrong?
im trying to make a "button" that you can click and not click (obviously). when im giving the commend to click its not working... the code: clicked = False def click(): clicked = True def un_click(): clicked = False click() if clicked == True: print ("the button is clicked...") else: print ("the button is not clicked")
3 Respuestas
+ 4
try this
clicked = False
def click():
global clicked
clicked = True
def un_click():
global clicked
clicked = False
click()
if clicked == True:
print ("the button is clicked...")
else:
print ("the button is not clicked")
why "global clicked" inside function?
Because python is over-smart and assume that we are making a new local variable "clicked" rather than assuming "clicked" as global.
****************************************************
But remember this has nothing to do with printing global variable.
for example:
s = "Hello"
def func() :
print(s)
func()
output:
Hello
Note: we don't need to declare "global s" inside the func since we are only printing
****************************************************
Only when assignment/changing the global variable inside function you need to declare the variable as global inside the function where you are assignment or changing it
+ 5
The way you wrote it, you define three 'clicked' variables: one in the global context, one in the context of click() method and one in the context of un_click() method.
In order for both methods to relate to the same, global variable, you have to add:
global clicked
as the first row in each method definition:
def click():
global clicked
clicked = True
0
RKK , thank you!