Tkinter按钮点击时无法将输入值传递给函数的问题
Hey there! I see the issue you're hitting with your Tkinter code—let's get it sorted out quickly.
The Core Problem
Right now, when you write self.e_name = Entry(self.master).grid(row=0, column=1), you're assigning the return value of grid() (which is always None) to your self.e_name variable, not the actual Entry widget object. Tkinter's layout methods (grid, pack, place) don't return the widget they're called on—they just handle positioning, so you need to split these into two separate steps.
Corrected Code Example
Here's how to adjust your code to properly reference the Entry widgets and bind the button to a function that grabs their values:
# First, keep your original label code (it's working fine) Label(self.master, text="Name").grid(row=0, sticky=W) Label(self.master, text="Username").grid(row=1, sticky=W) Label(self.master, text="Email").grid(row=2, sticky=W) # Create Entry widgets FIRST, then call grid() on them self.e_name = Entry(self.master) self.e_name.grid(row=0, column=1) self.e_username = Entry(self.master) self.e_username.grid(row=1, column=1) self.e_email = Entry(self.master) self.e_email.grid(row=2, column=1) # Define a function to handle the button click def handle_login(self): # Get the values from each Entry widget name = self.e_name.get() username = self.e_username.get() email = self.e_email.get() # Do whatever you need with these values—print, validate, pass to another function, etc. print(f"Submitted: Name={name}, Username={username}, Email={email}") # Create the button and bind it to your handler function Button(self.master, text="Login", command=self.handle_login).grid(row=3, column=0, columnspan=2, padx=5, pady=5)
Key Takeaways
- Always separate widget creation from layout: Create the widget (like
Entry), assign it to a variable, then callgrid()/pack()/place()on that variable. - Use the
get()method on Entry widgets to retrieve the text the user entered. - The
commandparameter of a Button expects a callable (a function or method)—since this is in a class, we useself.handle_loginto reference the class method.
内容的提问来源于stack exchange,提问作者Robin
相关产品推荐
相关产品推荐

