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

如何为Tkinter应用设置多区域差异化背景?

Solution for Multi-Colored Background in Tkinter

Hey there! To get that light gray top section plus dark lower background effect you want, Tkinter doesn’t let you set multiple background colors directly on the root window. Instead, we’ll use Frame widgets to split the window into distinct regions—each with its own background color. Here’s how to adjust your code step by step:

Modified Code with Multi-Color Background

import tkinter as tk

root = tk.Tk()
root.title("Arizon")
root.geometry("620x400+0+0")

# 1. Create top frame for the heading (light gray background)
top_frame = tk.Frame(root, bg="#e0e0e0", height=80)
top_frame.pack(fill="x")  # Stretch across the full window width

# 2. Add the heading to the top frame
heading = tk.Label(
    top_frame, 
    text="Arizon Updater", 
    font=("arial", 40, "bold"), 
    fg="#030208", 
    bg="#e0e0e0"
)
heading.pack(pady=10)  # Add vertical padding to center the heading

# 3. Create main content frame (dark background for the rest)
main_frame = tk.Frame(root, bg="#1c1b1c")
main_frame.pack(fill="both", expand=True)  # Fill all remaining window space

# 4. Add your input label to the main frame
label1 = tk.Label(
    main_frame, 
    text="Enter how much minimum value do u want to gain: ", 
    font=("arial", 9, "bold"), 
    fg="#f0f0f5", 
    bg="#1c1b1c"
)
label1.place(x=5, y=10)  # Adjust y-position since main frame starts below the top section

root.mainloop()

Key Details to Note:

  • Frames as Containers: We use two frames to split the UI:
    • top_frame: Takes the top area with a light gray (#e0e0e0) background, sized to fit the heading.
    • main_frame: Occupies the rest of the window with your original dark background (#1c1b1c).
  • Layout Control:
    • pack(fill="x") ensures the top frame stretches horizontally across the window.
    • pack(fill="both", expand=True) makes the main frame fill all remaining space, even if the window is resized.
  • Fixing Widget Assignment: I separated widget creation and layout calls (e.g., heading = Label(...) then heading.pack()) because using .pack()/.place() directly in the assignment returns None, which breaks future references to the widget.

Bonus Tip for Fixed Top Frame Height:

If you want to lock the top frame to a specific height (regardless of the heading size), add top_frame.pack_propagate(False) right after creating the top frame. This prevents the frame from resizing to fit its child widgets.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:57:27