简体   繁体   English

如何更新循环中创建的按钮和标签的 Tkinter 参数?

[英]How do you update Tkinter parameters for buttons and labels created in a loop?

Once an instance of a button has been created in a loop how is an individual button or label updated?在循环中创建按钮实例后,如何更新单个按钮或 label? Lets say I want to change the background on the 'North' button to 'blue'.假设我想将“北”按钮的背景更改为“蓝色”。

?????????.config(bg = 'blue')

What is the button name for the 'North' button in the code below?下面代码中“北”按钮的按钮名称是什么?

import tkinter as tk

def onbutton_click(label):
    print('selected ', label)

lst = ['North','South','East','West']
win = tk.Tk()
win.title = 'Compass'
for col,Direction in enumerate(lst):
    buttonName = tk.Button(win, text=Direction, command=lambda e=Direction: onbutton_click(e))
    buttonName.grid(row=0, column=col)

win.mainloop()

This code is from another question answered by gms - thank you, that was a great answer, very clear!此代码来自 gms 回答的另一个问题 - 谢谢,这是一个很好的答案,非常清楚! Tkinter create buttons from list each with its own function Tkinter 从列表中创建按钮,每个按钮都有自己的 function

You need some sort of reference to the button objects in order to access and modify them, after they are created in the loop.在循环中创建它们之后,您需要对按钮对象进行某种引用才能访问和修改它们。

One idea is to put them inside a dictionary whose key is the direction:一个想法是将它们放在一个字典中,字典的键是方向:

import tkinter as tk
    
def onbutton_click(label):
    print('selected ', label)

lst = ['North','South','East','West']
win = tk.Tk()
win.title = 'Compass'

button_dict = {}

for col,Direction in enumerate(lst):
    buttonName = tk.Button(win, text=Direction, command=lambda e=Direction: onbutton_click(e))
    buttonName.grid(row=0, column=col)
    button_dict[Direction] = buttonName

button_dict['North'].config(bg='blue')

win.mainloop()

Try this:尝试这个:

import tkinter as tk

def onbutton_click(label):
    print('selected ', label)
    if label == "North":
        # because "North" is the first item of `lst` we
        # know that we can use 0 as the idx
        buttons[0].config(text="new text here")

lst = ['North','South','East','West']
win = tk.Tk()
win.title = 'Compass'

# Create a list for all of the buttons
buttons = []

for col,Direction in enumerate(lst):
    buttonName = tk.Button(win, text=Direction, command=lambda e=Direction: onbutton_click(e))
    buttonName.grid(row=0, column=col)

    buttons.append(buttonName)

win.mainloop()

I created a dictionary of all of the buttons and directions like this: {"North": <Button>, "South": <Button>} .我创建了一个包含所有按钮和方向的字典,如下所示: {"North": <Button>, "South": <Button>} Then I used <dict>["North"] to get the button with the "North" label.然后我使用<dict>["North"]来获取带有 "North" label 的按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM