You need to enable JavaScript to run this app. 如何在Tkinter中为挂载在Canvas上的Frame添加并正常显示控件
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tkinter中为挂载在Canvas上的Frame添加并正常显示控件

问题原因

你遇到的问题核心是Canvas不会自动感知内部嵌套Frame的尺寸变化:

  • 你当前仅给Canvas绑定了<Configure>事件,只有Canvas自身尺寸发生变化时才会更新滚动区域scrollregion
  • 点击按钮往second_frame新增Label时,变化的是内部嵌套的second_frame的尺寸,Canvas本身尺寸没有改变,不会触发滚动区域更新,Canvas无法感知到内部Frame新增了内容,因此不会显示新增的控件。
修复方案

只需要给内部嵌套的second_frame也绑定<Configure>事件,只要Frame尺寸发生变化(新增/删除控件都会触发),就同步更新Canvas的滚动区域即可:
在你创建second_frame的代码后新增一行绑定逻辑:

second_frame = Frame(background)
background.create_window(150,100, window=second_frame, anchor='nw')
# 新增下面这行
second_frame.bind('<Configure>', lambda e: background.configure(scrollregion = background.bbox('all')))
修正后完整可运行代码
from tkinter import *
from tkinter import ttk

#Creating main window
root = Tk()
root.resizable(width=False, height=False)

#Defining Background
toolbar = Frame(root, width=613, height=114)
toolbar.grid(row=0, column=0)

background_frame = Frame(root, width=615, height=560)
background_frame.grid(row=1, column=0)

background = Canvas(background_frame, width=615, height=560)
background.pack(side=LEFT, fill=BOTH, expand=1)

scroll_bar = ttk.Scrollbar(background_frame, orient=VERTICAL, command=background.yview)
scroll_bar.pack(side=RIGHT, fill=Y)

background.configure(yscrollcommand=scroll_bar.set)

second_frame = Frame(background)
background.create_window(150,100, window=second_frame, anchor='nw')
# 新增内部Frame尺寸变化监听
second_frame.bind('<Configure>', lambda e: background.configure(scrollregion = background.bbox('all')))

def confirm1():
    for x in range(100): 
        Label(second_frame, text = x ).grid(row=x, column=1)

show_labels = Button(toolbar, text= "Show labels", fg="black", command=confirm1)
show_labels.grid(row=0, column=2)

root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 12:06:05