python - 如何滚动浏览在函数内部定义的 tkinter 小部件?
问题描述
我用两个框架创建了一个主根。
一帧用于程序工具栏。
另一个框架用于显示数据的画布和滚动条小部件。
画布内部是第三个较小的框架,用于滚动数据。
但是,当我尝试在函数调用中定义新的小部件时,滚动按钮会失去其功能。仅当我在代码的顶层定义这些小部件时,那个较小的框架才可滚动。
我使用了一个简单的 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()
单击按钮并滚动画布区域后的结果:
推荐阅读
- python - 将二进制格式的 word2vec 向量导入 spacy
- php - 通过字符对齐问题写入文本字符
- angular - 如何将数据传递给组件到另一个组件
- cordova-plugins - 在 MicroBlink 框架中找不到 Armv7 和 Arm64 的符号
- python - 运行示例 python-telegram-bot 代码时发生错误
- javascript - 从日期对象中仅获取小时和分钟
- apache-spark - 调用其他笔记本时Databricks笔记本超时错误:com.databricks.WorkflowException:java.net.SocketTimeoutException:读取超时
- python - 严格增加列表中相邻元素之间的差异
- php - 如何在自定义助手或指令中获取 Laravel 中的视图数据
- amazon-web-services - IAM - 如何限制对队列创建的访问?