【问题标题】:Get contents of a Tkinter Entry widget获取 Tkinter 条目小部件的内容
【发布时间】:2022-12-08 01:43:40
【问题描述】:

我正在创建一个应用程序,我想在 GUI Entry 小部件中使用输入的值。

如何从 Tkinter Entry 小部件获取输入?

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

root.mainloop()

【问题讨论】:

标签: python python-3.x tkinter tkinter-entry


【解决方案1】:

您需要做两件事:保留对小部件的引用,然后使用 get() 方法获取字符串。

这是一个例子:

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

【讨论】:

    【解决方案2】:

    这是一个例子:

    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()
    

    【讨论】:

    • 这个答案是由 Bryan Oakley 从 this other one 无耻地复制的。
    【解决方案3】:

    首先声明一个所需类型的变量。例如一个整数:

    变量 = IntVar()

    然后:

    入口=入口(根,文本变量=var)

    条目.pack()

    user_input = var.get()

    根.mainloop()

    希望这可以帮助。

    【讨论】:

    • 这是否会为当前的答案添加任何内容@aleksandarkrumov
    猜你喜欢
    • 1970-01-01
    • 2012-04-06
    • 2023-03-22
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    相关资源
    最近更新 更多