Tkinter登录窗口点击登录报错:缺少1个必需位置参数window
Hey there, let's break down what's going on with your code and fix that error!
The Root Cause
When you set command=enter for your Login button, Tkinter calls the enter function without passing any arguments by default. But your enter function is defined to require a window parameter—hence the TypeError: enter() missing 1 required positional argument: 'window' message.
Quick Fix: Use lambda to Pass the Argument
The simplest way to pass the window parameter to your enter function is to use a lambda function as the command. Lambda acts as a small wrapper that calls enter with the correct argument when the button is clicked.
Here's how to modify the button line:
btn=tk.Button(text='Login',command=lambda: enter(window))
Full Modified Code
Here's your complete code with the fix applied, plus a few small improvements to make the new window work properly:
import tkinter as tk def enter(window): if ipt.get()=='admin' and ipt1.get() == 'admin': window.destroy() # Create and configure the new logged-in window new_window = tk.Tk() new_window.title("Logged In Successfully") new_window.geometry('1000x600+260+100') new_window.resizable(0, 0) # Start the event loop for the new window new_window.mainloop() window=tk.Tk() window.title("Login") window.geometry('200x80') window.resizable(0,0) lbl = tk.Label(text='Name:') lbl.grid(row=0,column=0) lbl1=tk.Label(text='Password:') lbl1.grid(row=1,column=0) ipt=tk.Entry() ipt.grid(row=0,column=1) ipt1=tk.Entry(show='*') ipt1.grid(row=1,column=1) # Use lambda to pass the login window to the enter function btn=tk.Button(text='Login',command=lambda: enter(window)) btn.grid(row=2,column=1) window.mainloop()
Key Notes:
- I renamed the new window variable to
new_windowto avoid confusion with the original login window. - Added
new_window.mainloop()to start the event loop for the new window—without this, the new window would close immediately after creation. - Added window titles to both windows so you can easily distinguish between them.
内容的提问来源于stack exchange,提问作者Tan Joo Hui

