我正在用tkinter在python中做一个GUI,我想为按钮上的每一次点击做+1。这是完整的代码:
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()正在windows 10上运行python3.6。
发布于 2020-04-08 09:58:35
clickbtn是一个函数,因此它确实是不可迭代的,它所做的就是将按钮单击绑定到回调函数--它不会接收任何事件。
这里的解决方案非常简单,使用绑定到按钮单击的回调来更新变量:
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()https://stackoverflow.com/questions/61097424
复制相似问题