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?
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.
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.
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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With