Python 3.7中Tkinter的.get()方法返回空值求助
Hey there, sorry you’ve been stuck on this for 2 hours—Tkinter has some easy-to-miss quirks with input widgets, especially around scope and timing, which are super common for folks new to GUI programming. Let’s walk through the most likely causes and quick checks you can do right now, even without sharing your full code:
Common Causes & Fixes
Widget Scope Issues
If yourEntrywidget is defined inside a function (like a setup or init function) but isn’t stored as a global variable or a class attribute (e.g.,self.entry), the reference to it might get lost by the time you call.get(). For example, if you create the entry in a function and don’t assign it to a persistent variable, Python’s garbage collector might clean it up, leaving you with an empty value when you try to access it later.Timing Mismatch
Tkinter is event-driven—if you’re calling.get()immediately when your program starts (before the user has a chance to type anything), it’ll naturally return an empty string. Make sure you only call.get()in response to a user action, like a button click (via thecommandparameter) or a key press event.Accidental Clearing
Double-check if there’s any code that calls.delete(0, tk.END)on the entry widget before you call.get(). It’s easy to accidentally add a clear command that runs right before you try to fetch the input.Incorrect Widget Reference
If you’ve created multipleEntrywidgets, make sure you’re calling.get()on the correct one. It’s easy to mix up variable names if you have several inputs for your database.
Quick Test to Isolate the Problem
Try running this minimal Tkinter script to confirm that .get() works as expected in a simple setup:
import tkinter as tk def fetch_input(): print("Input value:", entry.get()) root = tk.Tk() # Create entry widget and keep a persistent reference entry = tk.Entry(root) entry.pack(padx=10, pady=10) # Button to trigger input fetch submit_btn = tk.Button(root, text="Get Input", command=fetch_input) submit_btn.pack(pady=5) root.mainloop()
If this works, the issue is definitely in how your entry widget is defined or accessed in your full code.
Since you can’t share your full code publicly for plagiarism reasons, sending it to your email makes total sense. When you do, make sure to include:
- The exact code where you define the
Entrywidget - The code that calls
.get()and handles the database save - How you’ve set up the user event that triggers the save (like a button’s
commandbinding)
That will help pinpoint exactly where the disconnect is between your input widget and the .get() call.
内容的提问来源于stack exchange,提问作者Cyril Alexander

