从条目小部件保存变量

时间:2016-05-03 00:54:41

标签: python tkinter

我希望将此输入框的文本输入保存到列表中然后进行打印。我不能在按下按钮时保存输入,它只打印占位符变量。

 names = []

 from tkinter import*

 class Trip:
     def __init__(self, parent):
        E_name = "q"
        self.En_name = "g"
        self.En_name = str(self.En_name)
        self.go = Frame(parent, width = 500, height = 450, bg = "snow", pady = 30, padx = 10)
        self.go.grid(row = 1, column = 0)
        self.go.grid_propagate(0) # to reserve space required for frame
        self.tet = Frame(parent, width = 500, height = 450, bg = "snow")

        name = Label(self.go, text = "Name:", bg = "snow")
        name.grid(row = 1, column = 0, sticky = E)
        self.E_name = Entry(self.go, width = 40, textvariable = self.En_name)
        self.E_name.grid(row = 1, column = 1, sticky = W, pady = 4)


        menuButton = Button(self.go, text = "Continue", command = self.breakeverything)
        menuButton.grid(row = 8, column = 1, pady = 4)

     def breakeverything(self):
        names.append(self.En_name)
        print (names[0])
        self.E_name.delete(0, "end")

 #main routine
 if __name__ == "__main__":
    root = Tk()
    root.title("Traveller Details")
    play = Trip(root)
    root.geometry("500x450+0+0")
    root.mainloop()

2 个答案:

答案 0 :(得分:2)

textvariable应该是tkinter.StringVar(),而不是原始字符串。您的应用程序看起来很简单,甚至不需要它。取出self.En_name,取出textvariable,然后只检索Entrybreakeverything()窗口小部件的当前值(不再是合适的名称):

def breakeverything(self):
    names.append(self.E_name.get())
    print(names[-1]) # printing the last name in the list seems more useful
    self.E_name.delete(0, "end")

我还建议将names移动到Trip.__init__并使其成为与其他所有内容一样的实例变量self.names = []。它可以更容易地跟踪范围。

答案 1 :(得分:1)

您错误地使用textvariable(您必须使用其中一个特殊的Tkinter变量,例如StringVar),但您根本不需要使用它。只需保存对窗口小部件的引用,然后在需要值时调用get方法:

self.E_name = Entry(self.go, width = 40)
...
print("you entered: " + self.E_name.get())

如果您坚持使用textvariable,请使用StringVar,然后在其上调用get方法:

self.En_name = StringVar()
self.E_name = Entry(..., textvariable=self.En_name)
...
print("you entered: " + self.En_name.get())