首页 > 解决方案 > 如何为通过 for 循环 Tkinter 生成的每个小部件分配名称

问题描述

我在 Python 中很新,我现在有一个问题,我正在尝试通过 for 循环为列表中的每个项目制作一个小部件 Notebook,但问题是我无法为每个小部件分配名称,我需要在每个 Notebook 小部件中放置不同小部件的小部件名称。

正如我所说,我是 python 中的菜鸟,我认为下面的代码是一团糟:),所以谢谢你们的帮助。

from tkinter import ttk
note = ttk.Notebook()

list=["tab1","tab2"]

def show_parent_name():
    name= button2.winfo_parent()
    print(name)

for i in (list):
        name_tab=i

        tab = ttk.Frame(note, name=name_tab)   #-----name define the widget
        note.add(tab, text=nombre_tab)   # ---text define the tab name
        note.pack()

        global button2
        button2 = Button(tab, text="print parent name",command=show_parent_name)
        button2.grid(row=0, column=0, sticky=W)

note.mainloop()

标签: pythonpython-3.xtkinter

解决方案


有几件事:list是一个内置函数。如果您将list其用作变量名,则该函数将不再可供您使用。

我也在导入 tkinter,因为使用了来自 tkinter 的对象和常量。

lambda用来编写按钮回调,它允许我将选项卡名称作为参数传递给show_parent_name函数。然后我也不需要全局变量。

我重写了循环变量的用法,因为它比必要的复杂。

Tk()如果你没有明确地这样做,Tkinter 将自动创建窗口根 ( )。但是如果你打算对窗口做任何事情,除了包含笔记本之外,你应该明确地创建它。

试试这个代码,看看它是否按照你想要的方式工作:

from tkinter import *
from tkinter import ttk

note = ttk.Notebook()
alist = ["tab1","tab2"]

def show_parent_name(name):
    print(name)

for name_tab in alist:
    tab = ttk.Frame(note, name=name_tab)   #-----name define the widget
    note.add(tab, text=name_tab)   # ---text define the tab name
    note.pack()

    button2 = Button(tab, text="print parent name",
                     command=lambda name_tab=name_tab: show_parent_name(name_tab))
    button2.grid(row=0, column=0, sticky=W)

note.mainloop()

推荐阅读