I have an example. It does not work and I do not understand why.

from tkinter import * def function(): root = Tk() but = Button(root,text="Test question", width=30, height=5,) but.pack() def why(event): a = 1 but.bind("<Button-1>", why) root.mainloop() if a == 1: print("all works") 
  • @Alban when I put global before a, I see an error global a = 1 ^ SyntaxError: invalid syntax - Bernard
  • one
    not specifically before а , but on the line above - Pavel Durmanov

2 answers 2

The function does not see the variable a , since it is defined outside its local scope and is not global. In order for the code to work before a = 1 you need to add global a , but there is one thing but all works will be printed only after you close the window, after clicking on the button. To see the output when you click a button, you need to define the behavior directly in the function why() . Here is a small example:

 In [55]: def function(): ...: values = {'a':0} ...: root = Tk() ...: but = Button(root,text="Test question", width=30, height=5,) ...: but.pack() ...: def why(event): ...: values['a'] +=1 ...: if values['a'] % 2 == 0: ...: print('Hello!!!') ...: else: ...: print('World!!!') ...: but.bind("<Button-1>", why) ...: root.mainloop() 
     from tkinter import * def function(): a = 0 root = Tk() but = Button(root,text="Test question", width=30, height=5,) but.pack() def why(event): nonlocal a a += 1 print('a:', a) but.bind("<Button-1>", why) root.mainloop()