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

如何在Tkinter的二级窗口中通过函数创建按钮?

Fixing Tkinter Error When Adding Widgets to a Toplevel Window Separately

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:

  1. When creating the Label, you didn't specify its parent window (the master parameter). By default, Tkinter will attach it to your main window instead of sec_window.
  2. The grid() method doesn't take the parent window as its first argument. To specify which window the widget belongs to via grid, you'd use the in_ 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:28:09