【问题标题】:Can not make vertical scroll work on canvas无法在画布上进行垂直滚动
【发布时间】:2016-03-27 17:56:56
【问题描述】:

我想在 Canvas 中放置例如 20 个文本框。所以我的小部件层次结构是主窗口-> 画布-> 文本框。文本框无法全部放入画布中,因此我想在其上附加一个垂直滚动条。这是我尝试过的:

from tkinter import *
root = Tk()
root_height = root.winfo_screenheight()
root_width = root.winfo_screenwidth()
root.geometry("%dx%d+0+0" % (root_width, root_height))

canvas = Canvas(root, height=root_height, width=root_width)
canvas.pack(fill=BOTH, expand=1)

scrollbar = Scrollbar(canvas)
scrollbar.pack(side=RIGHT, fill=Y)
canvas.config(yscrollcommand=scrollbar.set)

textBoxes = []

for i in range(0, 20):
    textBoxes.append(Text(canvas, height=1, width=20, bd=2))

y_offset = 15
for i in range(0, 20):
    textBoxes[i].place(x=10, y=y_offset)
    y_offset += 60

scrollbar.config(command=canvas.yview)


mainloop()

所以基本上,我试着做我从教程和其他问题中理解的东西 -

  1. 将小部件的(画布)yscrollcommand 回调设置为滚动条的 set 方法。

  2. 将滚动条的命令设置为小部件(画布)的yview方法。

不幸的是,滚动条无法点击。我哪里错了,我怎样才能达到预期的行为?

【问题讨论】:

    标签: python tkinter tcl tk


    【解决方案1】:

    您可以使用包含所有Text 对象的单独Frame 小部件。然后在Canvas 中调用.create_window 方法,将Frame 设置为window 参数。

    from tkinter import *
    
    root = Tk()
    root_width = root.winfo_screenwidth()
    root_height = root.winfo_screenheight()
    
    canvas = Canvas(root)
    canvas.pack(side=LEFT, fill=BOTH, expand=True)
    
    scrollbar = Scrollbar(root, orient=VERTICAL)
    scrollbar.pack(side=RIGHT, fill=Y)
    
    frame = Frame(canvas)
    frame.pack(fill=BOTH, expand=True)
    
    def resize(event):
        canvas.configure(scrollregion=canvas.bbox(ALL))
    
    canvas.create_window((0, 0), window=frame, anchor=NW)
    
    canvas.config(yscrollcommand=scrollbar.set)
    scrollbar.config(command=canvas.yview)
    frame.bind('<Configure>', resize)
    
    for i in range(20):
        text = Text(frame, width=30, height=1)
        text.grid(row=i, pady=i*10)
    
    mainloop()
    

    【讨论】:

      【解决方案2】:

      滚动条只滚动画布对象。它不会滚动使用packplacegrid 在画布内添加的小部件。要使小部件可滚动,必须使用canvas.create_window(...) 添加它。

      【讨论】:

      • 您能帮我修改一下我的代码示例吗?
      猜你喜欢
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      • 2020-09-08
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多