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")

7th Jun 2020, 5:06 PM
Yahel
Yahel - avatar
3 Answers
+ 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
7th Jun 2020, 5:19 PM
RKK
RKK - avatar
+ 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
7th Jun 2020, 5:19 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
0
RKK , thank you!
7th Jun 2020, 6:04 PM
Yahel
Yahel - avatar