Get contents of a Tkinter Entry widget

心已入冬 提交于 2019-11-26 06:46:26

问题


I am creating an application and I want to use the entered values in the GUI Entry widget.

How do I get the entered input from a Tkinter Entry widget?

root = Tk()
...
entry = Entry(root)
entry.pack()

root.mainloop()

回答1:


You need to do two things: keep a reference to the widget, and then use the get() method to get the string.

Here's an example:

self.entry = Entry(...)
...
print("the text is", self.entry.get())



回答2:


Here's an example:

import tkinter as tk

class SampleApp(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        print(self.entry.get())

w = SampleApp()
w.mainloop()



回答3:


First declare a variable of required type. For example an integer:

var = IntVar()

Then:

entry = Entry(root, textvariable=var)

entry.pack()

user_input = var.get()

root.mainloop()

Hope this helps.



来源:https://stackoverflow.com/questions/9815063/get-contents-of-a-tkinter-entry-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!