如何在Tkinter的二级窗口中通过函数创建按钮?
Hey there! Let's break down what's going wrong in your code and get it working properly—good news is, you absolutely can create a separate function to add widgets to your secondary window; you just need to fix a couple of small syntax issues.
First, Let's Diagnose the Error
The _tkinter.TclError you're seeing comes from two mistakes in your create_secondwindow_button function:
- When creating the
Label, you didn't specify its parent window (themasterparameter). By default, Tkinter will attach it to your main window instead ofsec_window. - The
grid()method doesn't take the parent window as its first argument. To specify which window the widget belongs to viagrid, you'd use thein_parameter—but it's cleaner to set the parent when creating the widget directly.
Here's the Corrected Function
def create_secondwindow_button(): # 1. Specify sec_window as the parent when creating the Label screenshot_snap = Label(sec_window, text = "dog") # 2. Use grid without passing the window as the first argument screenshot_snap.grid(column = 1, row = 1, padx=10, pady=10) # Added padx/pady for better spacing
Even Better: Avoid Global Variables (Optional)
While using the global sec_window works, it's often cleaner to pass the window object directly as a parameter to your function. This avoids relying on global state, which can make your code more maintainable:
def open_win2(): sec_window = Toplevel() sec_window.config(height = 1800,width = 1800, bg = "chocolate1") sec_picture_box = Label(sec_window,height=800, width=800, image=mainview) sec_picture_box.place(x=800, y=100) return sec_window # Return the window object to reference elsewhere # Modify the function to accept the parent window as an argument def create_secondwindow_button(parent_window): screenshot_snap = Label(parent_window, text = "dog") screenshot_snap.grid(column = 1, row = 1, padx=10, pady=10) # When setting up your main window button, use lambda to pass the window reference: sec_window = open_win2() # Store the secondary window object main_btn = Button(root, text="Add Label to Second Window", command=lambda: create_secondwindow_button(sec_window)) main_btn.pack()
Key Takeaway
You don't need to embed your widget creation logic inside the open_win2 function. As long as the secondary window (sec_window) exists when you call your separate function, you can add widgets to it freely—you just need to make sure the widget knows which window it belongs to when you create it.
内容的提问来源于stack exchange,提问作者link

