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

Tkinter应用中设置的黑色Frame组件无法显示问题求助

问题原因

Frame组件在未显式指定宽高、且内部没有任何子控件撑开尺寸的情况下,默认会收缩为宽高均为0的极小区域,因此你设置的黑色背景无法被看到。

解决方法

有两种常用的修改方案:

方案1:创建Frame时直接指定尺寸

在初始化Frame时添加width和height参数设定大小,示例如下:

from tkinter import *

app=Tk()

screen_width=app.winfo_screenwidth()
screen_height=app.winfo_screenheight()
print(screen_height, screen_width)
app.geometry("%dx%d" % (screen_width,screen_height))

# 新增width和height参数,这里设置为和窗口等大
frame=Frame(app, bg='black', width=screen_width, height=screen_height)
frame.pack()

app.mainloop()

方案2:通过pack参数让Frame自动撑满父窗口

如果需要Frame自适应窗口大小,调用pack方法时添加fill和expand参数,无需手动指定固定尺寸:

from tkinter import *

app=Tk()

screen_width=app.winfo_screenwidth()
screen_height=app.winfo_screenheight()
print(screen_height, screen_width)
app.geometry("%dx%d" % (screen_width,screen_height))

frame=Frame(app, bg='black')
# fill=BOTH 表示横向纵向都填充父容器剩余空间,expand=True表示允许占满父容器全部可用空间
frame.pack(fill=BOTH, expand=True)

app.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:06:02