我有一个可以更改的选项卡名称列表,因此我想循环遍历这些名称并创建选项卡。其中,我想放置根据用户单击的选项卡而变化的各种按钮。我的问题是我的选项卡无法加载。如果我删除该命令,我的窗口可以正常加载正确的选项卡。
我的代码:
import tkinter as tk
from tkinter import ttk
def loadtab(event):
selection = event.widget.select()
tabN = event.widget.tab(selection, "text")
t_nos=str(uFrame.index(uFrame.select())+1)
tab = f'tab{t_nos}'
if tabN == 'Ed':
tk.Button(tab, text=tabN).pack()
elif tabN == 'Ted':
tk.Button(tab, text=tabN).pack()
root = tk.Tk()
root.title("Tab")
uFrame = ttk.Notebook(root, style="TFrame") #Create notebook
uFrame.pack(pady=20)
uFrame.bind("<<NotebookTabChanged>>", loadtab) #Bind notebook so that when it is changed, it loads items onto each tab
pathOpt = ['Ed', 'Ted'] #Tab names
tNo = 0 #Counter
for name in pathOpt: #parse through tab names and create tabs
tab = f'tab{tNo + 1}'
tab = ttk.Frame(uFrame)
uFrame.add(tab, text=pathOpt[tNo])
tNo += 1
test = tk.Button(root, text='Deliniate tabs') # placeholder to show where tabs are
test.pack(pady=20)
root.mainloop()
结果:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\cwade\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "C:\PyProjects\TemplateTool\TemplateToolV3_Tabs.py", line 12, in loadtab
tk.Button(tab, text=tabN).pack()
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\cwade\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 2707, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "C:\Users\cwade\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 2623, in __init__
self._setup(master, cnf)
File "C:\Users\cwade\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 2592, in _setup
self.tk = master.tk
^^^^^^^^^
AttributeError: 'str' object has no attribute 'tk'
我已经打印了各种名称等,发现选项卡名称是正确的,但我仍然收到错误。
在
loadtab()
内部,为 tab
变量分配一个字符串,然后将其用作新创建按钮的父级。它会导致异常。
您需要使用
.nametowidget()
获取框架的实例:
def loadtab(event):
# selection is the name of the frame
selection = event.widget.select()
tabN = event.widget.tab(selection, "text")
#t_nos=str(uFrame.index(uFrame.select())+1)
#tab = f'tab{t_nos}'
# get the instance of the frame using .nametowidget()
tab = event.widget.nametowidget(selection)
if tabN == 'Ed':
tk.Button(tab, text=tabN).pack()
elif tabN == 'Ted':
tk.Button(tab, text=tabN).pack()