【发布时间】:2017-12-24 11:01:18
【问题描述】:
我尝试在每个单元格上绘制一个带有标记的 3x3 小板。 此标记应仅在用鼠标触摸单元格时显示。 这工作一次,两次,有时 3 次,但随后事件循环无限“触发”(总是相同的事件)......
import tkinter as tk
cellsize = 50
class Board(tk.Canvas):
def __init__(self):
tk.Canvas.__init__(self)
for row in range(3):
for column in range(3):
ulx, uly = column*cellsize, row*cellsize
lrx, lry = ulx+cellsize, uly+cellsize
_cell = self.create_rectangle(ulx, uly, lrx, lry,
fill='green')
_right = self.create_rectangle(ulx+39, uly+20, lrx-1, lry-20,
fill='red',
state='hidden')
self.tag_bind(_cell, '<Enter>',
lambda e, r=_right: self.show_pos('on', r))
self.tag_bind(_cell, '<Leave>',
lambda e, r=_right: self.show_pos('off', r))
def show_pos(self, onoff, right):
print('{} {}'.format(onoff, right))
if onoff == 'on':
self.itemconfig(right, state='normal')
elif onoff == 'off':
self.itemconfig(right, state='hidden')
root = tk.Tk()
Board().grid()
root.mainloop()
也许这是坚持 self.itemconfigure 语句,因为做其他事情(例如更新状态行)按预期工作。
有解决办法吗?
提前谢谢
马文
补充:
更准确地说:它似乎坚持使用 'state=..."
将“show_pos”中的 itemconfig 更改为“fill=...”按预期工作。
所以标题应该是
'canvas.itemconfig(state='...' 导致无限事件循环'
【问题讨论】:
-
因为在状态更改(Tkinter.py,def _cnfmerge)之后调用“更新”,您的状态更改会导致额外的状态更改 - 足够快地运行鼠标会导致您的循环。尝试通过鼠标位置计算而不是进入/离开来实现绑定,你应该很好。
标签: python tkinter python-3.5 tkinter-canvas