[英]tkinter scrollbar has no bar to scroll with
当我创建滚动条时,似乎没有滚动选项,即使其中的内容比 canvas 大。 canvas 在框架内,因为我听说这是正确执行此操作的方法。 我的代码的相关部分:
from tkinter import *
class UniversityProcessor:
def __init__(self):
self.root = Tk()
self.rootWidth, self.rootHeight = 1200, 1200
screenWidth, screenHeight = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
xPosition, yPosition = (screenWidth/2) - (self.rootWidth/2), (screenHeight/2) - (self.rootHeight/2)
self.root.geometry("%dx%d+%d+%d"%(self.rootWidth, self.rootHeight, xPosition, yPosition))
self.root.title("University processor")
self.updateUniText()
self.root.mainloop()
def updateUniText(self):
self.textPixelTotal = 0
self.frame = Frame(self.root, bg = self.bg, width = self.rootWidth, height = self.rootHeight)
self.frame.pack()
self.canvas = Canvas(self.frame, bg = self.bg, width = self.rootWidth, height = self.rootHeight)
self.inner = Frame(self.canvas, bg = self.bg, width = self.rootWidth, height = self.rootHeight)
self.canvas.create_window((0, 0), window = self.inner, anchor = "nw")
for it in range(0, 50):
label = Label(self.inner, bg = self.bg, text = f"Title {it + 1}", font = ("Arial", 20, "bold"))
label.place(y = self.textPixelTotal, x = it)
self.canvas.update()
self.textPixelTotal += label.winfo_height()
self.inner.configure(height = self.textPixelTotal)
self.inner.place(x=0,y=0,anchor="nw")
self.scroll = Scrollbar(self.frame, orient = VERTICAL, command = self.canvas.yview)
self.scroll.pack(side = RIGHT, fill = Y)
self.canvas.configure(yscrollcommand = self.scroll.set)
self.canvas.bind("<Configure>", lambda e: self.canvas.configure(scrollregion = self.canvas.bbox("all")))
self.canvas.pack(side=LEFT, expand=True, fill=BOTH)
UniversityProcessor()
我不知道是否需要设置某种 canvas 属性或滚动条属性,但它会填满屏幕......
滚动条确实出现了,它的大小是正确的,但是实际上没有滚动
您不应使用place()
将标签放在 canvas 内。 您需要在 canvas 内部创建一个内部框架,并将所有标签放在该框架内:
def updateUniText(self):
textPixelTotal = 0
self.frame = Frame(self.root, width=self.rootWidth, height=self.rootHeight)
self.frame.pack()
self.background = Canvas(self.frame, width=self.rootWidth, height=self.rootHeight)
# an internal frame inside canvas
self.internal = Frame(self.background)
self.background.create_window(0, 0, window=self.internal, anchor="nw")
# create labels inside the internal frame
for i in range(0,200):
label = Label(self.internal, bg=self.bg, text=f"Title {i+1}", font=("Arial", 20, "bold"))
label.pack(anchor="w")
self.background.update()
self.scroll = Scrollbar(self.frame, orient=VERTICAL)
self.scroll.pack(side=RIGHT, fill=Y)
self.scroll.config(command=self.background.yview)
self.background.config(width=self.rootWidth-20, height=self.rootHeight)
self.background.config(yscrollcommand=self.scroll.set, scrollregion=self.background.bbox("all"))
self.background.pack(side=LEFT, expand=True, fill=BOTH)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.