Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

python - Why is Tkinter Entry's get function returning nothing?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...