tkinter中的事件和绑定不能在循环中工作

2024-09-28 13:19:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用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个按钮。活页夹只对最后一个按钮有效。有人知道我怎么用活页夹把所有的钮扣都贴上吗?在


Tags: textselfinittkinterdefframerowscolor
1条回答
网友
1楼 · 发布于 2024-09-28 13:19:04

您在color_change1中使用self.bat,但是self.bat保留了最后一个按钮,因为您在循环中重写了它。但您将所有按钮保留在self.panels[x]中,以访问任何按钮。所以你可以用它。在

但有一个更简单的解决方案-绑定使用变量event向执行的函数发送有关事件的一些信息。例如,event.widget允许您访问执行函数color_change1的小部件,以便您可以使用它:

def color_change1(self, event):
    event.widget.configure(bg = "red")

参见第Events and Bindings页的“事件属性”

相关问题 更多 >

    热门问题