def stand():
e1 = Tkinter.Entry(main_window)
e1.grid(row =6, column=3)
e2 = Tkinter.Entry(main_window)
e2.grid(row =7, column=3)
e3 = Tkinter.Entry(main_window)
e3.grid(row =8, column=3)
e4 = Tkinter.Entry(main_window)
e4.grid(row =9, column=3)
e5 = Tkinter.Entry(main_window)
e5.grid(row = 10, column = 3)
e6 = Tkinter.Entry(main_window)
e6.grid(row=11, column = 3)
p1 = Tkinter.Label (main_window)
p1.grid(row = 6, column =2)
p2 = Tkinter.Label (main_window)
p2.grid(row =7, column =2)
p3 = Tkinter.Label (main_window)
p3.grid(row = 8, column =2)
p4 = Tkinter.Label (main_window)
p4.grid(row =9 , column =2)
p5 = Tkinter.Label (main_window)
p5.grid(row =10 , column =2)
p6 = Tkinter.Label (main_window)
p6.grid(row =11 , column =2)
我需要删除这些并用不同的条目/标签替换它们,方法是按下一个删除那里的条目/标签并添加新条目/标签的按钮。我已经尝试了所有方法,但无法找到解决方案:
NameError: global name 'e1' is not defined
有什么想法吗?
答案 0 :(得分:0)
您可以在错误消息中看到问题:解释器认为e1
是全局名称(以及其他小部件),但您在本地范围内的stand()
内定义了它,因此你的程序的其他部分不知道它。有多种解决方案。一种解决方案是使其全球化:
e1 = Tkinter.Entry(main_window)
def stand():
global e1
e1.grid(row =6, column=3)
我不喜欢这样做。另一种解决方案是采用面向对象的方法:
class App(object):
...
def stand():
self.e1 = Tkinter.Entry(main_window)
self.e1.grid(row =6, column=3)
def access():
print(self.e1) # can access it
另一个解决方案是将小部件作为参数传递给其他函数:
def stand():
self.e1 = Tkinter.Entry(main_window)
self.e1.grid(row =6, column=3)
def access(widget):
print(widget)
最后,您应该通过重新配置小部件来重新配置小部件,而不是删除小部件并创建新小部件:
e1.config(width=30)
p1.config(text="New Text")