python - 无法在 Canvas 上进行垂直滚动

标签 python tkinter tcl tk-toolkit

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

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. 将小部件( Canvas )的 yscrollcommand 回调设置为滚动条的 set 方法。

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

不幸的是,滚动条似乎无法点击。我错在哪里以及如何实现所需的行为?

最佳答案

您可以使用包含所有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()

关于python - 无法在 Canvas 上进行垂直滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36250674/

相关文章:

python - 如何将函数应用于多个 Pandas 数据框

python - 在字典键中搜索元素

python - 使用DataNitro,如何打印python循环到excel,确保打印23行后,打印移动到相邻列?

shell - Expect 中的后台生成进程

tcl - upvar 命令在 TCL 中是如何工作的?

tcl - 如何从tcl中的字符串中剪切子字符串

python - 不规则分箱 p2 python pandas

python - 使用 "browse"按钮在 Tkinter 中显示文件路径 - Python

python - 在 TKinter 中格式化异步选项卡?

python - Tkinter TkinterHtml 无法运行