手动插入框架集滚动条无法正常工作 [英] Manually inserting into frame sets scrollbar to not work tkinter

查看:89
本文介绍了手动插入框架集滚动条无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果窗口小部件在自动运行期间(在运行时?)插入框架,我有一个带有滚动条的代码可以正常工作.但是,一旦我通过按下按钮添加了小部件,它就不起作用了.在这里看看:

I have a code with scrollbar that works correctly, if the widgets are inserted onto the frame during automatically(during runtime?). But once I add widgets by pressing a button, it does not work. Take a look here:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry("500x400")

def more():
    tk.Button(second_frame,text='MORE').pack()

main_section = tk.Frame(root,bg='white')
main_section.pack()

scroll_frame = tk.Frame(main_section,bg='white')
scroll_frame.grid(row=3,column=0)

# Create A Canvas
my_canvas = tk.Canvas(scroll_frame,bg='white',borderwidth=0)
my_canvas.pack(side='left', fill='both', expand=1)

# Add A Scrollbar To The Canvas
my_scrollbar = ttk.Scrollbar(scroll_frame, orient='vertical', command=my_canvas.yview)
my_scrollbar.pack(side='right', fill='y')

# Configure The Canvas
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

# Create ANOTHER Frame INSIDE the Canvas
second_frame = tk.Frame(my_canvas,bg='white')

# Add that New frame To a Window In The Canvas
my_canvas.create_window(0,0, window=second_frame, anchor="nw")

tk.Button(second_frame,text='Click for more buttons',command=more).pack()

root.mainloop()

在这里,一旦您按下按钮并创建了更多按钮,滚动条就不会激活,但是如果在主块中给出循环,则滚动条将被激活.例如:

Here once you press the button and more buttons are created the scrollbar does not become active but if you give a loop in the main block, the scrollbar will get active. For example:

for a in range(30):
    tk.Button(second_frame,text=a).pack()

如果您想知道为什么会有很多帧,可以从较大的代码中取出来制作MCVE.我在这里做什么错了?在此先感谢:D

If your wondering why are there alot of frames, this is taken out of a bigger code to make a MCVE out. What am I doing here wrong? Thanks in advance :D

推荐答案

此事件从未触发:

my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

当您知道函数向 second_frame 添加按钮时,原因就很简单了,这就是为什么 second_frame 将配置为 width 高度.

The reason is fairly easy when you know that your function adds buttons to second_frame and thats why second_frame will be configured in width and height.

因此,您在定义second_frame之后需要以下行:

so you need this line after defining the second_frame:

second_frame.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

这篇关于手动插入框架集滚动条无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆