簡體   English   中英

如何更新循環中創建的按鈕和標簽的 Tkinter 參數?

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

在循環中創建按鈕實例后,如何更新單個按鈕或 label? 假設我想將“北”按鈕的背景更改為“藍色”。

?????????.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 從列表中創建按鈕,每個按鈕都有自己的 function

在循環中創建它們之后,您需要對按鈕對象進行某種引用才能訪問和修改它們。

一個想法是將它們放在一個字典中,字典的鍵是方向:

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

嘗試這個:

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" label 的按鈕。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM