python - 如何为通过 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()
解决方案
有几件事: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()
推荐阅读
- linux - 从 linux shell 脚本中的文本文件打印下一个序列号
- flutter - 通过 ListView.Builder Flutter 搜索文本和高亮匹配
- powershell - 获取少数用户所属的 DL 列表
- bitbucket - Bitbucket:如何显示团队提交?
- laravel - docker上的主管redis异常
- java - 致命异常:主要 java.lang.NoClassDefFoundError:android.media.AudioAttributes$Builder
- r - 删除了包含非有限值的 N 行 (stat_pie)
- android - 如何在底部应用栏中关闭工厂?
- php - 在 memcached 重新启动后,Libmemached 滞后未从服务器获取缓存值
- c# - CheckBox 根据选定对象的值创建一个字符串