tkinter 滚动条不起作用并且始终保持活动状态

The tkinter scrollbar doesn't work and remains active throughout

我已经检查了 this 个问题,但它没有回答我的问题

我有以下代码:

from tkinter import *
root = Tk()
root.geometry("800x600")
Scr = Scrollbar(root)
Scr.pack(side = RIGHT,fill =Y)
cnvs = Canvas(root,width = 800,height = 560,yscrollcommand = Scr.set)
cnvs.place(x=0,y=40)
for i in range(100):
    x = Label(cnvs,text=f"This is label {i}")
    x.pack()
Scr.config(command = cnvs.yview)
root.mainloop()

当我 运行 这样做时,滚动条不起作用并且始终处于非活动状态。

我做错了什么?

有几件事:

当您想滚动放置在 canvas 上的小部件时,您应该使用 canvas 方法,例如 create_text() 而不是 pack()grid() 它们,否则他们不会滚动。

然后你必须提供 canvas 一个滚动区域。首先将对象放在 canvas 上,然后定义 scrollregion。

from tkinter import *

root = Tk()
root.geometry('300x200+800+50')

mainframe = Frame(root)
mainframe.pack(pady=10, padx=10, expand='yes', fill='both')
# Making sure only canvas will change with window size
mainframe.grid_columnconfigure(0, weight=1)
mainframe.grid_rowconfigure(0, weight=1)

scr = Scrollbar(mainframe, orient='vertical')
scr.grid(column=1, row=0, sticky='ns')

canvas = Canvas(mainframe, bg='khaki', yscrollcommand=scr.set)
canvas.grid(column=0, row=0, sticky='ewns')
scr.config(command=canvas.yview)

for i in range(100):
    # Create canvas objects at canvas positions
    canvas.create_text(0, 20*i, text=f"This is label {i}", anchor='w')
    # Create objects and pack them, will NOT scroll
    x = Label(canvas,text=f"Will not scroll {i}")
    x.pack()

# Define scrollregion AFTER widgets are placed on canvas
canvas.config(scrollregion=canvas.bbox('all'))

root.mainloop()