You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter按钮点击时无法将输入值传递给函数的问题

Fixing Tkinter Entry Value Retrieval & Button Binding

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 call grid()/pack()/place() on that variable.
  • Use the get() method on Entry widgets to retrieve the text the user entered.
  • The command parameter of a Button expects a callable (a function or method)—since this is in a class, we use self.handle_login to reference the class method.

内容的提问来源于stack exchange,提问作者Robin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:35:08