0

I'm doing a GUI in python with tkinter, and I want to do +1 for every click on the buttons. This is the complete code:

import tkinter as tk
from tkinter import *

cat=tk.Button(window, text='Cat', height=2)
cat.config()
cat.pack(fill=X)
cube=tk.Button(window, text='Cube',  height=2)
cube.config()
cube.pack(fill=X)
def printed(event):
    print('Clicked!')
def clickbtn():
    cat.bind("<Button-1>", printed)
    cat.bind("<Button-2>", printed)
    cat.bind("<Button-3>", printed)
    cube.bind("<Button-1>", printed)
    cube.bind("<Button-2>", printed)
    cube.bind("<Button-3>", printed)
clickbtn()

for event in clickbtn:
    x=0
    x=x+1
window.mainloop()

Is working python 3.6 on windows 10.

3
  • 3
    I fail to see how this code (not even a proper minimal reproducible example FWIW] could "work". Commented Apr 8, 2020 at 9:35
  • @brunodesthuilliers I'm sorry, I edited it now, I putted some code, so you can execute it. Commented Apr 8, 2020 at 9:43
  • @ArionSintesSintes You're still missing window and X. Commented Apr 8, 2020 at 9:50

1 Answer 1

3

clickbtn is a function, so it's indeed not iterable, and all it does is to bind button clicks to a callback function anyway - it doesn't receive any event whatsoever.

The solution here is quite simply to use the callback you bind to button clicks to update your variable:

x = 0

def onclick(event):
    global x
    x += 1
    print('Clicked!')


def set_clickbtn_callback():
    for target in (cat, bind):
       for i in range(1, 3):
          btn = "<Button-{}>".format(i) 
          target.bind(btn, onclick)

set_clickbtn_callback()

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.