tkinter:未定义全局名称
当我尝试运行此代码时,总是收到错误消息。 我有 Tkinter 文档并已阅读它。我正在尝试将文本放入一个字段中,一旦有人开始输入,该字段就会消失。这是代码。
class MyGrid(Frame):
def __init__(self, win=None):
Frame.__init__(self, win)
self.grid()
self.mkWidgets()
def mkWidgets(self):
self.mytext = StringVar()
self.mytext.set("Enter text here")
self.e = Entry(bg='orange', textvariable=mytext, relief=SUNKEN, width=45)
self.e.grid(row=0, column=0)
app = MyGrid()
app.mainloop()
我总是收到此错误:
NameError: global name 'mytext' is not defined
I am always getting an error message when I try to run this code.
I have the Tkinter documentation and have read it. I am trying to put text into a field that will disappear once a person starts typing. Here is the code.
class MyGrid(Frame):
def __init__(self, win=None):
Frame.__init__(self, win)
self.grid()
self.mkWidgets()
def mkWidgets(self):
self.mytext = StringVar()
self.mytext.set("Enter text here")
self.e = Entry(bg='orange', textvariable=mytext, relief=SUNKEN, width=45)
self.e.grid(row=0, column=0)
app = MyGrid()
app.mainloop()
I always get this error:
NameError: global name 'mytext' is not defined
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的调试第一条规则:假设错误是真实的。在这种情况下,它表示
mytext
未定义。当我查看您的代码时,我必须同意:您没有在任何地方定义名为mytext
的全局变量。然而,您确实定义了名为
self.mytext
的内容。您应该在以下代码行中使用它:My first rule of debugging: assume the error is telling the literal truth. In this case it is saying
mytext
is undefined. When I look at your code I have to agree: nowhere do you define a global variable namedmytext
.You do, however, define something named
self.mytext
. You should use that in the following line of code:使用这个:
use this: