我正在尝试使用tkinter模块在循环中创建绑定.
from tkinter import * class Gui(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def Arrays(self,rankings): self.panels = {} self.helpLf = LabelFrame(self, text="Array Layout:") self.helpLf.grid(row=10, column=9, columnspan=5, rowspan=8) for rows in range(10): for cols in range(10): x = str(rows)+"_"+str(cols) self.row = Frame(self.helpLf) self.bat = Button(self.helpLf,text=" ", bg = "white") self.bat.grid(row=10+rows, column=cols) self.panels[x] = self.bat self.panels[x].bind('<Button-1>', self.make_lambda()) self.panels[x].bind('<Double-1>', self.color_change1) def color_change(self, event): """Changes the button's color""" self.bat.configure(bg = "green") def color_change1(self, event): self.bat.configure(bg = "red")这里有10X10 = 100个按钮.活页夹仅适用于最后一个按钮.有谁知道我该如何对所有按钮应用活页夹?
解决方案您在color_change1中使用了self.bat,但是self.bat保留了最后一个按钮,因为您将其写在了循环中.但是您将所有按钮都保留在self.panels[x]中,以便可以访问任何按钮.这样您就可以使用它.
但是有一个更简单的解决方案-绑定使用变量event将有关事件的某些信息发送到执行的函数.例如,event.widget允许您访问执行功能color_change1的窗口小部件,因此您可以使用它:
def color_change1(self, event): event.widget.configure(bg = "red")请参阅第事件和绑定 中的事件属性" >
I am trying to create binding in a loop using tkinter module.
from tkinter import * class Gui(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def Arrays(self,rankings): self.panels = {} self.helpLf = LabelFrame(self, text="Array Layout:") self.helpLf.grid(row=10, column=9, columnspan=5, rowspan=8) for rows in range(10): for cols in range(10): x = str(rows)+"_"+str(cols) self.row = Frame(self.helpLf) self.bat = Button(self.helpLf,text=" ", bg = "white") self.bat.grid(row=10+rows, column=cols) self.panels[x] = self.bat self.panels[x].bind('<Button-1>', self.make_lambda()) self.panels[x].bind('<Double-1>', self.color_change1) def color_change(self, event): """Changes the button's color""" self.bat.configure(bg = "green") def color_change1(self, event): self.bat.configure(bg = "red")There are 10X10= 100 buttons here. the binder works only for the last button. Does anyone know how can I apply the binder for all the buttons?
解决方案You use self.bat in color_change1 but self.bat keeps last button because you ovewrite it in loop. But you keep all buttons in self.panels[x] to have access to any button. So you could use it.
But there is simpler solution - binding use variable event to send some information about event to executed function. For example event.widget give you access to widget which execute function color_change1 so you can use it:
def color_change1(self, event): event.widget.configure(bg = "red")See "Event Attributes" on page Events and Bindings
更多推荐
tkinter中的事件和绑定无法循环运行
发布评论