python tkinter 如何更改特定网格空间上的小部件标签?

我有一个 3x3 的按钮网格,所有这些按钮都绑定到相同的事件函数。此函数根据单击的按钮更改特定按钮的标签。我希望能够通过查看按钮在网格上的位置(即行值和列值)来选择将影响哪些按钮。


例如,我希望能够说“考虑到点击的按钮是(第 1 行,第 2 列),我想更改(第 2 行,第 0 列)和(第 1 行,第 1 列)按钮的标签.


我知道如何找到被点击按钮的行和列:


import tkinter


def click(event):

    space = event.widget

    space_label = space['text']

    row = space.grid_info()['row'] #get the row of clicked button

    column = space.grid_info()['column'] #get the column of clicked button


board = tkinter.Tk()


for i in range(0,9): #creates the 3x3 grid of buttons


    button = tkinter.Button(text = "0")


    if i in range(0,3):

        r = 0

    elif i in range(3,6):

        r = 1

    else:

        r = 2


    button.grid(row = r, column = i%3)

    button.bind("<Button-1>",click)


board.mainloop()

但是我无法弄清楚如何只给定网格的一行和一列来访问按钮的标签。


PS 编码新手,抱歉,如果这很明显,我环顾四周但找不到任何足够相似的问题。


慕侠2389804
浏览 106回答 1
1回答

UYOU

如果您打算在创建一个小部件并将其添加到您的界面后对其进行任何操作,最好保留一个参考。这是对您的代码的修改,它创建了一个字典button_dict来存储您的每个按钮。键是元组(row,column)。我将button_dict作为附加输入添加到您的click函数中,并修改了按钮绑定以使用 包含这个新输入lambda。import tkinterdef click(event,button_dict):&nbsp; &nbsp; space = event.widget&nbsp; &nbsp; space_label = space['text']&nbsp; &nbsp; row = space.grid_info()['row'] #get the row of clicked button&nbsp; &nbsp; column = space.grid_info()['column'] #get the column of clicked button&nbsp; &nbsp; button = button_dict[(row,column)] # Retrieve our button using the row/col&nbsp; &nbsp; print(button['text']) # Print button text for demonstrationboard = tkinter.Tk()button_dict = {} # Store your button references herefor i in range(0,9): #creates the 3x3 grid of buttons&nbsp; &nbsp; button = tkinter.Button(text = i) # Changed the text for demonstration&nbsp; &nbsp; if i in range(0,3):&nbsp; &nbsp; &nbsp; &nbsp; r = 0&nbsp; &nbsp; elif i in range(3,6):&nbsp; &nbsp; &nbsp; &nbsp; r = 1&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; r = 2&nbsp; &nbsp; button.grid(row = r, column = i%3)&nbsp; &nbsp; button.bind("<Button-1>",lambda event: click(event,button_dict))&nbsp; &nbsp; button_dict[(r,i%3)] = button # Add reference to your button dictionaryboard.mainloop()如果您只对按下的按钮感兴趣,您可以简单地访问该event.widget属性。从你的例子来看,听起来你想修改每个事件的任意数量的按钮,所以我认为字典会给你更多的通用性。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python