我想在 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()
所以基本上,我尝试做我从教程和其他问题中理解的事情 -
将小部件( Canvas )的
yscrollcommand
回调设置为滚动条的 set 方法。将滚动条的命令设置为小部件( 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/