【问题标题】:Scrollbar on canvas画布上的滚动条
【发布时间】:2017-07-19 12:01:50
【问题描述】:

我目前正在尝试在画布上实现滚动条,因为我了解到我不能立即在框架上执行此操作。我可以让它出现,但我不能让它真正发挥作用。当谈到 python 和 tkinter 时,我仍然是一个初学者,之前关于这件事的帖子对我没有太大帮助。这是我的代码(我愿意就我所做的任何其他被认为是不好的做法的建议提出建议):

from tkinter import *

class myApp():
    def __init__(self,root):
        myApp.f2=Frame(root)
        myApp.f2.pack()
        myApp.canv=Canvas(self.f2)
        myApp.canv.pack()
        myApp.f1=Frame(self.canv)
        myApp.f1.pack(side=LEFT, fill=BOTH, expand=TRUE)
        myApp.scroll=Scrollbar(self.f1,orient=VERTICAL,
        command=myApp.canv.yview)
        myApp.scroll.grid(row=0,column=6)
        myApp.canv.config(yscrollcommand=myApp.scroll.set)

我必须为其余的小部件使用网格,我没有在这里包含。

【问题讨论】:

  • 你试图让滚动条成为画布的孙子(通过框架f1),这很奇怪——通常滚动条和它的滚动小部件是兄弟姐妹。此外,您通常不会通过 .grid().pack() 将子代添加到画布 - 您必须使用 .add_window() 创建实际滚动的子代。

标签: python-3.x tkinter


【解决方案1】:

我不太了解绑定是如何工作的,但这是我在 Toplevel 中用于滚动条的代码,它不是来自我,但我不记得我在哪里找到它(我认为它在 stackoverflow 上,你应该搜索更多,我相信你会找到一些东西)。它应该可以工作,但只有用鼠标悬停它才能滚动栏

    Toplevel = tk.Toplevel(self)

    #create canvas to make a scrollbar
    canvas = tk.Canvas(Toplevel, borderwidth=0)
    #create frame which will contains your widgets
    frame = tk.Frame(canvas)

    #create and pack your vsb to the Toplevel and link it to the canvas yview
    vsb = tk.Scrollbar(Toplevel, orient="vertical", command=canvas.yview)
    canvas.configure(yscrollcommand=vsb.set)
    vsb.pack(side="right", fill="y")
    canvas.pack(side="left", fill="both", expand=True)
    canvas.create_window((5,5), window=frame, anchor="nw")


    #i don't understand this line
    frame.bind("<Configure>", lambda event, canvas=canvas: canvas.configure(scrollregion=canvas.bbox("all")))

    #add your widgets to the frame
    ...

PS:不要使用from tkinter import *,您可以(并且将会)发生名称冲突,使用import tkinterimport tkinter as tk

编辑:this question 是我的来源。

【讨论】:

    猜你喜欢
    • 2011-12-05
    • 2017-07-03
    • 2014-04-21
    • 2017-01-18
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多