无法引用课程中的Entry字段?

时间:2015-07-21 21:20:54

标签: python tkinter nameerror tkinter-entry

我试图将全局变量设置为输入到Tkinter Entry字段中的值,但我收到以下错误:

  

NameError:全球名称' HealthEntry'未定义

以下是相关代码:

Health = 0

class window(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.parent = parent

        HealthEntry = Entry(self)

        testButton = Button(self, text = "entry field test", command = self.printHealth)
        testButton.grid(row=18, column=3)

    def printHealth(self):
        Health = HealthEntry.get()
        print Health

我也尝试将HealthEntry.get()更改为window.HealthEntry.get(),但这也不起作用。我做错了什么?

2 个答案:

答案 0 :(得分:2)

因为您的HealthEntry未定义为自我,所以基本上他是__init__方法的本地。

将其更改为:self.HealthEntry

def __init__(self, parent):
        Tk.__init__(self, parent)
        self.parent = parent

        self.HealthEntry = Entry(self)

        testButton = Button(self, text = "entry field test", command = self.printHealth)
        testButton.grid(row=18, column=3)

def printHealth(self):
    Health = self.HealthEntry.get()
    print Health

正如Padraic在他的回答中写道,你可能也希望将testButton用作类成员..

答案 1 :(得分:1)

将其设为实际属性并使用self.HealthEntry,您可能还希望对testButton self.testButton执行相同操作:

        self.HealthEntry = Entry()    
        self.testButton = Button(self, text = "entry field test", command = self.printHealth)
        self.testButton.grid(row=18, column=3)

    def printHealth(self):
        Health = self.HealthEntry.get()
        print Health

要使其在init方法之外全局访问,您需要在init方法global HealthEntry中使用global关键字,但正确的方法是使其成为上述属性。