Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 774
CodingCat Avatar asked May 23 '12 20:05

CodingCat


People also ask

What does get () do in Tkinter?

An Entry widget in Tkinter is nothing but an input widget that accepts single-line user input in a text field. To return the data entered in an Entry widget, we have to use the get() method. It returns the data of the entry widget which further can be printed on the console.

Why is my Tkinter not working?

The easiest way to fix this problem is by upgrading your python to use python 3. If upgrading python is not an option, you only need to rename your imports to use Tkinter (uppercase) instead of tkinter (lowercase). Output: As a result, this window proves that your python installation includes the Tkinter module.

How can I tell if Tkinter Mainloop is running?

If you know the process name, in Windows, you can use psutil to check if a process is running. if __name__ == "__main__": app_name = 'chrome' if is_running(name=app_name): if kill(name=app_name): print(f'{app_name} killed!

What does Mainloop () do in Tkinter?

mainloop() tells Python to run the Tkinter event loop. This method listens for events, such as button clicks or keypresses, and blocks any code that comes after it from running until you close the window where you called the method.


1 Answers

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.

like image 121
Bryan Oakley Avatar answered Oct 05 '22 20:10

Bryan Oakley