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

Tkinter如何创建占满剩余窗口空间的grid布局顶层Frame?

实现方案

核心修改逻辑

  • 调整Frame的pack顺序,先创建底部按钮Frame,再创建顶部内容Frame,避免布局挤压
  • 顶部内容Frame开启expand=True和fill=tk.BOTH属性,自动填充按钮上方的所有剩余空间
  • 给顶部内容Frame配置grid布局的行、列权重,实现庄家手牌区在上、玩家手牌区在下的均分布局

修改后的完整代码

import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image

def hit():
    print("hit was pressed")

def stand():
    print("stand was pressed")

def new_hand():
    print("new hand was pressed")

# 创建主窗口
window = tk.Tk()
window.title("Black Jack")
window.geometry("800x600")
window.configure(bg="#0C8702")

# 先创建底部按钮Frame,固定在窗口底部
buttons = ttk.Frame(window, padding=(20,10,20,0))
buttons.pack(side="bottom", fill="x")

hit_button = ttk.Button(buttons, text="Hit", command=hit)
hit_button.pack(side="left", fill="x", padx=5)

stand_button = ttk.Button(buttons, text="Stand", command=stand)
stand_button.pack(side="left", fill="x", padx=5)

deal_new_hand_button = ttk.Button(buttons, text="New Hand", command=new_hand)
deal_new_hand_button.pack(side="left", fill="x", padx=5)

quit_button = ttk.Button(buttons, text="Quit", command=window.destroy)
quit_button.pack(side="left", fill="x", padx=5)

# 创建顶部内容Frame,占满按钮上方所有空间
content_frame = ttk.Frame(window)
# 如需显示边框调试,可添加参数borderwidth=2, relief="solid"
content_frame.pack(fill=tk.BOTH, expand=True)
# 配置grid布局权重:2行1列,两行高度均分,列宽度占满
content_frame.grid_rowconfigure(0, weight=1)
content_frame.grid_rowconfigure(1, weight=1)
content_frame.grid_columnconfigure(0, weight=1)

# 庄家手牌区:放在第0行
dealer_frame = ttk.Frame(content_frame)
dealer_frame.grid(row=0, column=0, sticky="nsew")
# 测试用庄家卡牌,可后续替换为逻辑生成的卡牌
dealer_card_test = Image.open("PNG/2C.png").resize((80, 120))
dealer_card_img = ImageTk.PhotoImage(dealer_card_test)
dealer_card_label = tk.Label(dealer_frame, image=dealer_card_img, bg="#0C8702")
dealer_card_label.image = dealer_card_img
dealer_card_label.pack(side="left", padx=5, pady=20)

# 玩家手牌区:放在第1行
player_frame = ttk.Frame(content_frame)
player_frame.grid(row=1, column=0, sticky="nsew")
# 玩家两张测试卡牌
image1 = Image.open("PNG/2C.png").resize((80, 120))
real_img = ImageTk.PhotoImage(image1)
panel1 = tk.Label(player_frame, image=real_img, bg="#0C8702")
panel1.image = real_img
panel1.pack(side="left", padx=5, pady=20)

image2 = Image.open("PNG/2D.png").resize((80, 120))
real_img2 = ImageTk.PhotoImage(image2)
panel2 = tk.Label(player_frame, image=real_img2, bg="#0C8702")
panel2.image = real_img2
panel2.pack(side="left", padx=5, pady=20)

window.mainloop()

内容的提问来源于stack exchange,提问作者David Em-Yinn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:36:01