|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我要创建4个切换页,明明生成了4个变量名,引用的时候却提示未定义,不明白问题在哪import tkinter as tk
import tkinter.ttk as ttk
class App(tk.Tk):
def __init__(self):
super().__init__()
tests = ['test1', 'test2', 'test3', 'test4']
self.tabControl = ttk.Notebook(self, width=30, padding=2)
for i, each_test in enumerate(tests):
locals()[f'tabs{i}'] = tk.Frame(self.tabControl)
self.tabControl.add(locals()[f'tabs{i}'], text=each_test)
self.tabControl.grid(column=0, row=0, padx=5, pady=5)
print(locals())
print(tab0)
if __name__ == '__main__':
app = App()
app.mainloop()
你的变量名少打了一个 s,研究了一伙,不太清楚这里局部变量为什么找不到,那改成这样吧:
import tkinter as tk
import tkinter.ttk as ttk
class App(tk.Tk):
def __init__(self):
super().__init__()
tests = ['test1', 'test2', 'test3', 'test4']
self.tabControl = ttk.Notebook(self, width=30, padding=2)
for i, each_test in enumerate(tests):
locals()[f'tabs{i}'] = tk.Frame(self.tabControl)
self.tabControl.add(locals()[f'tabs{i}'], text=each_test)
self.tabControl.grid(column=0, row=0, padx=5, pady=5)
print(locals())
print(locals()["tabs0"])
if __name__ == '__main__':
app = App()
app.mainloop()
或者这样:
import tkinter as tk
import tkinter.ttk as ttk
class App(tk.Tk):
def __init__(self):
super().__init__()
tests = ['test1', 'test2', 'test3', 'test4']
self.tabControl = ttk.Notebook(self, width=30, padding=2)
for i, each_test in enumerate(tests):
self.__dict__[f'tabs{i}'] = tk.Frame(self.tabControl)
self.tabControl.add(self.__dict__[f'tabs{i}'], text=each_test)
self.tabControl.grid(column=0, row=0, padx=5, pady=5)
print(self.tabs0)
if __name__ == '__main__':
app = App()
app.mainloop()
|
-
-
|