Tkinter报错:按钮未知选项-command,请求Python3代码调试帮助
Hey there! Let's get that button working smoothly. The error you're seeing is a straightforward case-sensitivity issue—super easy to fix once you spot it.
What's Causing the Error?
Tkinter widget options are case-sensitive, and the correct parameter name for linking a button's click action is lowercase command, not uppercase COMMAND. When you use COMMAND=btn_clicked, Tkinter doesn't recognize it as a valid button option, which throws the "Unknown option -command" message.
Corrected Code
Here's your code with the fix applied:
from tkinter import * root = Tk() e = Entry(root, width=20) e.grid(row=0, column=0) def btn_clicked(): label = Label(root, text=f"Hello {e.get()}!") label.grid(row=1, column=0) # Changed uppercase COMMAND to lowercase command button = Button(root, padx=10, text="Click this", command=btn_clicked) button.grid(row=0, column=1) root.mainloop()
Quick Optimization Tip
Right now, every button click creates a new Label that stacks on top of the old ones. For a cleaner interface, you can initialize a single label once and update its text instead:
from tkinter import * root = Tk() e = Entry(root, width=20) e.grid(row=0, column=0) # Initialize an empty label upfront result_label = Label(root, text="") result_label.grid(row=1, column=0) def btn_clicked(): # Update the existing label's text instead of making a new one result_label.config(text=f"Hello {e.get()}!") button = Button(root, padx=10, text="Click this", command=btn_clicked) button.grid(row=0, column=1) root.mainloop()
内容的提问来源于stack exchange,提问作者ihsan




