为什么 Tkinter Entry 的 get 函数什么都不返回? [英] Why is Tkinter Entry's get function returning nothing?

查看:28
本文介绍了为什么 Tkinter Entry 的 get 函数什么都不返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Entry 字段来获取手动输入,然后处理该数据.

I'm trying to use an Entry field to get manual input, and then work with that data.

我发现的所有来源都声称我应该使用 get() 函数,但我还没有找到一个简单的工作迷你示例,我无法让它工作.

All sources I've found claim I should use the get() function, but I haven't found a simple working mini example yet, and I can't get it to work.

我希望有人能告诉我我做错了什么.这是一个小文件:

I hope someone can tel me what I'm doing wrong. Here's a mini file:

from tkinter import *


master = Tk()

Label(master, text="Input: ").grid(row=0, sticky=W)

entry = Entry(master)
entry.grid(row=0, column=1)

content = entry.get()
print(content)  # does not work

mainloop()

这给了我一个 Entry 字段,我可以输入,但一旦输入数据,我就无法对数据做任何事情.

This gives me an Entry field I can type in, but I can't do anything with the data once it's typed in.

我怀疑我的代码不起作用,因为最初 entry 是空的.但是,一旦输入数据,我该如何访问输入数据?

I suspect my code doesn't work because initially, entry is empty. But then how do I access input data once it has been typed in?

推荐答案

您似乎对何时运行命令感到困惑.在您的示例中,您在 GUI 有机会显示在屏幕上之前调用了 get 方法(这发生在您调用 mainloop 之后.

It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.

尝试添加一个调用 get 方法的按钮.如果您将应用程序编写为类,这会容易得多.例如:

Try adding a button that calls the get method. This is much easier if you write your application as a class. For 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())

app = SampleApp()
app.mainloop()

运行程序,在条目小部件中键入,然后单击按钮.

Run the program, type into the entry widget, then click on the button.

这篇关于为什么 Tkinter Entry 的 get 函数什么都不返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆