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

主类中第二个Frame内的Widget无法显示问题求助

解决Tkinter中新增Frame内Widget无法显示的问题

Hey there, let's break down why your coin_button_1 isn't showing up and fix it step by step.

问题根源分析

Your code has two key issues hiding the widget in your new Frame:

  1. 背景Label完全遮挡了Frame: 你用back_ground_img_label.pack(fill="both", expand=True)让背景Label占满了整个主窗口,之后self.frame用pack()添加时会被挤到背景Label的下方——但背景Label已经占满了所有空间,导致Frame完全不可见,里面的按钮自然也看不到。
  2. Frame的层级与布局未正确设置: 创建Frame时没有显式指定父容器(虽然默认是主窗口,但显式指定更清晰),且即使指定了,Frame也会被压在背景Label下面,没有办法透出内容。

修复后的代码

下面是调整后的代码,关键修复点都加了注释:

import tkinter as tk

class MainApplication(tk.Tk):
    def __init__(self):
        super().__init__()
        # 添加背景图片
        self.background_img = tk.PhotoImage(file="in office.png")
        back_ground_img_label = tk.Label(self, image=self.background_img)
        back_ground_img_label.pack(fill="both", expand=True)
        
        # 窗口位置调整
        width_of_window = 1012
        height_of_window = 604
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()
        x_coordinate = int((screen_width / 2) - (width_of_window / 2))
        y_coordinate = int((screen_height / 2) - (height_of_window / 2) - 30)
        self.geometry(
            f"{width_of_window}x{height_of_window}+{x_coordinate}+{y_coordinate}"
        )
        
        # 创建bet_frame并将其置于背景Label上层
        self.bet_frame()
        self.frame.lift()  # 把Frame移到背景Label的上方
        
        # 主窗口中的Label(添加了文字和背景色方便调试查看)
        bet_value_label_bg = tk.Label(self, text="主窗口测试Label", bg="white")
        bet_value_label_bg.place(x=462, y=300)
        
        # Frame内的按钮(添加了文字和背景色方便调试查看)
        coin_button_1 = tk.Button(self.frame, text="1 Coin", bg="yellow")
        coin_button_1.place(x=233, y=435)

    def bet_frame(self):
        # 显式指定主窗口为父容器,用透明背景不遮挡底层图片
        self.frame = tk.Frame(self, width=1012, height=604, bg="transparent")
        self.frame.pack(fill="both", expand=True)  # 让Frame和背景Label一样铺满窗口

if __name__ == "__main__":
    MainApplication().mainloop()

关键修复点说明

  • 显式指定父容器: 创建self.frame时传入self作为第一个参数,确保它属于主窗口。
  • Frame布局与层级调整: 用pack(fill="both", expand=True)让Frame和背景Label一样铺满窗口,再调用self.frame.lift()把Frame移到背景Label的上层,这样里面的控件就能显示在背景图之上了。
  • 调试可见性优化: 给Label和Button添加了文字和背景色,方便你直观看到它们的位置,实际使用时可以去掉这些调试属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:33:34