繁体   English   中英

如何滚动 function 中定义的 tkinter 小部件?

[英]How to scroll through tkinter widgets that were defined inside of a function?

我创建了一个有两个框架的主根。

  • 一帧用于程序工具栏。

  • 另一个框架用于显示数据的 canvas 和滚动条小部件。

  • canvas 内部是第三个较小的框架,用于滚动槽数据。

但是,当我尝试在 function 调用中定义新的小部件时,滚动按钮失去了它的功能。 仅当我在代码的顶层定义这些小部件时,较小的框架才可滚动。

我使用一个简单的 for 循环来创建仅用于测试的标签。

谁能告诉我我做错了什么?

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)
background.bind('<Configure>', lambda e:background.configure(scrollregion = background.bbox('all')))

second_frame = Frame(background)
background.create_window(150,100, window=second_frame, anchor='nw')


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()

每当您将小部件添加到scrollregion时,您都需要更新背景画布的滚动second_frame 通过绑定到框架的<Configure>事件很容易做到这一点。

这是您的代码的完整版本,添加了几行 ( # WHERE INDICATED ) 来执行此操作:

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)
# NOT NEEDED
#background.bind('<Configure>',
#                lambda e: background.configure(scrollregion=background.bbox('all')))

second_frame = Frame(background)
background.create_window(150,100, window=second_frame, anchor='nw')

# ADDED
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()

单击按钮并滚动 canvas 区域后的结果:

显示所有小部件现在都在滚动区域中的屏幕截图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM