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

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

问题描述

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



我发现的所有消息都声称我应该使用 get()函数,但是我还没有找到一个简单的工作小例子,而且我无法获取它工作。



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

pre $ from tkinter import *


master = Tk()

标签(master,text =Input:).grid(row = 0,sticky = W)

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

content = entry.get()
print(content)#不起作用

mainloop()

这给我一个我可以输入的条目字段,但我无法对数据进行任何操作。



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

解决方案

看起来您可能会对命令运行。在您的示例中,在GUI有机会显示在屏幕上之前调用 get 方法(发生在调用 mainloop



尝试添加一个调用 get 方法的按钮。例如:

  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()
$ b $ def on_button(self ):
print(self.entry.get())

app = SampleApp()
app.mainloop()

运行程序,输入入口小部件,然后点击按钮。


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

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

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

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?

解决方案

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.

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天全站免登陆