gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:53:10 25 4
gpt4 key购买 nike

我想在 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. 将滚动条的命令设置为 widget(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com