簡體   English   中英

Python3 - Tkinter - 使用字典創建小部件

[英]Python3 - Tkinter - Widget creation with a dict

我試圖在 tkinter 的根tkinter上動態創建小部件,並使用json文件作為小部件配置。 我簡化了代碼,因此您也可以進行測試。 (我在我的主要代碼中使用了grid()但這里沒有必要)

json 文件包含一個items列表,每個小部件都在一個單獨的字典中,它可以看起來像這樣的例子。

new_dict = {
    "items": [
        {
            "type": "frame",
            "id": "f1"
        },
        {
            "type": "button",
            "id": "b1",
            "text": "Button1"
        }
    ]
}

我的目標是創建一個小部件,存儲在id字段的value中,這樣我以后可以通過.config()更改小部件狀態或其他內容

(示例: f1 = Frame(root)

對於此示例,我的代碼如下所示:

注意:我使用locals()來創建特定變量,如果有更好的方法,請告訴我)

# Example: Change Frame Color to Blue
def change_background(frame_id):
    locals()[frame_id].config(bg=blue)

# Root Window
root = Tk()
root.geometry("800x600")

# Widget Creation
for item in new_dict["items"]:
    if item["type"] == "frame":
        frame_id = item["id"]
        locals()[item["id"]] = Frame(root, width=200, height=200, bg="green")
        locals()[item["id"]].pack(side=BOTTOM, fill=BOTH)
    elif item["type"] == "button":
        locals()[item["id"]] = Button(root, text=item["text"], command=lambda: change_background(frame_id))
        locals()[item["id"]].place(x=50, y=50, anchor=CENTER)

root.mainloop()

現在我的問題是我無法將frame id提供給change_background function。如果我這樣做,我會收到以下錯誤:

KeyError: 'f1'

我不太明白這里的問題,因為pack()place()grid()對每個小部件都能正常工作。

正如名字locals的意思,它只存儲局部變量。 所以 function 中的locals()只包含在 function 中定義的局部變量。

不建議像這樣使用locals() 只需使用普通字典即可:

...
# Example: Change Frame Color to Blue
def change_background(frame_id):
    widgets[frame_id].config(bg="blue")

# Root Window
root = Tk()
root.geometry("800x600")

# Widget Creation
# use a normal dictionary instead of locals()
widgets = {}
for item in new_dict["items"]:
    if item["type"] == "frame":
        frame_id = item["id"]
        widgets[item["id"]] = Frame(root, width=200, height=200, bg="green")
        widgets[item["id"]].pack(side=BOTTOM, fill=BOTH)
    elif item["type"] == "button":
        widgets[item["id"]] = Button(root, text=item["text"], command=lambda: change_background(frame_id))
        widgets[item["id"]].place(x=50, y=50, anchor=CENTER)
...

暫無
暫無

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

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