【问题标题】:Why can't I set the background of a ttk Frame?为什么我不能设置 ttk Frame 的背景?
【发布时间】:2021-08-13 02:31:42
【问题描述】:

这是我的代码:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", lambda: on_closing(root, btn))
frame1 = tk.Frame(root, bg=root['background'])
frame1.pack(expand="YES")

canvas = tk.Canvas(frame1, width=200, height=300, relief="sunken", bd=0, bg=root['background'])
scroll_y = tk.Scrollbar(frame1, orient="vertical", command=canvas.yview, bg=canvas['background'])
scroll_y.pack(side="right", fill='y')
canvas.pack(side="top", expand='YES', fill='both')
canvas.configure(yscrollcommand=scroll_y.set)
# canvas.update_idletasks()
# canvas.yview_moveto('1.0')
s = ttk.Style()
s.configure("new.TFrame", background=canvas['background'], width=canvas.winfo_width(), height=canvas.winfo_height())
msgFrame = ttk.Frame(canvas, style="new.TFrame")
msgFrame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=msgFrame, anchor="nw")

为什么框架不会改变它的颜色?还是它的宽度/高度?

如果您想在框架中添加一些字符串:

for i in range (50):
   lbl = tk.Label(msgFrame, text="example").pack()

【问题讨论】:

  • 使用canvas.config(bg=&lt;background colour&gt;)
  • 首先当你调用s.configure(...)时,canvas.winfo_width()canvas.winfo_height()是1(你可以使用print()来显示它们)。第二个widthheight 不能使用s.configure() 设置,而是在ttk.Frame(...) 中指定它们。同样出于调试目的,为它们使用不同的颜色。
  • 这些都不起作用...
  • msgFrame.pack(fill="both", expand="yes") 并使用另一种颜色。我认为你没有定义颜色(所以我用green 测试了它没有任何问题)
  • @JoeMo 通常pack/grid/place 不用于将小部件放入Canvas。像 OP 一样使用create_window(...)

标签: python python-3.x tkinter ttk


【解决方案1】:

首先对所有小部件使用相同的背景颜色很难看到效果。出于调试目的,为不同的小部件使用不同的背景颜色。

其次,您不能使用style.configure() 设置ttk::Framewidthheight,请在ttk::Frame(...) 中指定它们。

以下是根据您的代码修改的示例:

import tkinter as tk
from tkinter import ttk

def on_closing(root):
    root.destroy()

root = tk.Tk()
root.geometry("400x400")
root.config(bg="cyan")
root.protocol("WM_DELETE_WINDOW", lambda: on_closing(root))

frame1 = tk.Frame(root, bg="red")
frame1.pack(expand="YES")

canvas = tk.Canvas(frame1, width=200, height=300, relief="sunken", bd=0, bg="green")
scroll_y = tk.Scrollbar(frame1, orient="vertical", command=canvas.yview, bg=canvas['background'])
scroll_y.pack(side="right", fill='y')
canvas.pack(side="top", expand='YES', fill='both')
canvas.configure(yscrollcommand=scroll_y.set)
s = ttk.Style()
s.configure("new.TFrame", background="blue")
msgFrame = ttk.Frame(canvas, style="new.TFrame", width=100, height=200) # set width and height
msgFrame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=msgFrame, anchor="nw")

root.mainloop()

还有输出:

【讨论】:

    猜你喜欢
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2014-07-03
    • 2019-06-25
    • 1970-01-01
    • 2011-01-16
    相关资源
    最近更新 更多