【发布时间】: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=<background colour>) -
首先当你调用
s.configure(...)时,canvas.winfo_width()和canvas.winfo_height()是1(你可以使用print()来显示它们)。第二个width和height不能使用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