tkinter中动态变量定义后报错
我要创建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() = tk.Frame(self.tabControl)
self.tabControl.add(locals(), 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() = tk.Frame(self.tabControl)
self.tabControl.add(locals(), 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__ = tk.Frame(self.tabControl)
self.tabControl.add(self.__dict__, text=each_test)
self.tabControl.grid(column=0, row=0, padx=5, pady=5)
print(self.tabs0)
if __name__ == '__main__':
app = App()
app.mainloop() 找到了一篇文章对locals的解读
https://www.jb51.net/article/158474.htm
我更喜欢第二种方法
页:
[1]