【问题标题】:How do you update Tkinter parameters for buttons and labels created in a loop?如何更新循环中创建的按钮和标签的 Tkinter 参数?
【发布时间】:2021-05-25 23:34:43
【问题描述】:

在循环中创建按钮实例后,如何更新单个按钮或标签?假设我想将“北”按钮的背景更改为“蓝色”。

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

下面代码中“北”按钮的按钮名称是什么?

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()

此代码来自 gms 回答的另一个问题 - 谢谢,这是一个很好的答案,非常清楚! Tkinter create buttons from list each with its own function

【问题讨论】:

    标签: python function tkinter button label


    【解决方案1】:

    在循环中创建按钮对象后,您需要对按钮对象进行某种引用才能访问和修改它们。

    一个想法是将它们放在以方向为键的字典中:

    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()
    

    【讨论】:

    • 你为什么用button_dict[Direction] = buttonName而不是button_dict.update({Direction: buttonName})?只是好奇
    • @TheLizzard 它本质上是实现同一件事的两种方法。当我只有一对时,我更喜欢将键值对直接设置到字典中。如果我有多个键值对要更新,或者我事先已经有一个字典,我会使用dict.update(无需使用单个键值对创建字典,只需使用它来更新另一个字典和然后忘记它 - 只需直接设置值)。不过,最终这并不重要。
    • 这看起来非常干净且易于理解。谢谢 jfaccioni!
    【解决方案2】:

    试试这个:

    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()
    

    我创建了一个包含所有按钮和方向的字典,如下所示:{"North": <Button>, "South": <Button>}。然后我使用<dict>["North"] 来获取带有“North”标签的按钮。

    【讨论】:

    • 只是大声思考,是否可以使用列表或元组来代替字典?感谢您的输入 Lizzard!
    • @FordF-100 是的,我将更改我的答案以使用列表。如果您仍然需要字典的答案,请使用 jfaccioni 的答案。
    • 你们都超级有帮助!
    • StackOverFlow :D
    猜你喜欢
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多