简体   繁体   中英

Python Tkinter Canvas Many create_window() Items Not Scrolling with Scrollbar

Why doesn't the scrollbar initiate when create_window frame objects start to exceed the bottom self.container window?

My understanding is that widgets are scrollable if they are embedded on the canvas using create_window . For context, I don't want to create a scrolling frame - put all your widget in a frame, use create_window to add that frame to the canvas - because I intend to move these frame objects around on the canvas and leverage a lot of canvas capabilities. According to Effbot , You cannot draw other canvas items on top of a widget. , so if I had a scrolling frame, I wouldn't be able to put widgets on top of that.

So how do I scroll the canvas that contains many create_window objects, or, what am I doing wrong below?

import tkinter as tk

class Canvas_Scrollbar_CreateWindow(tk.Frame):

  def __init__(self, parent):
    tk.Frame.__init__(self, parent)
    self.parent = parent
    self.parent.columnconfigure(0, weight=1)
    self.grid_columnconfigure(0, weight=1)

    self.block_count = 0

    self.button = tk.Button(self, text='Add', command=self.addblock)
    self.button.grid(row=0, column=0, columnspan=2, sticky='new')

    self.container = tk.Frame(self)
    self.container.grid(row=1, column=0, sticky='nsew')

    self.canvas = tk.Canvas(self.container, width=200, height=450)
    self.scrollbar = tk.Scrollbar(self.container,
                                  orient='vertical',command=self.canvas.yview)
    self.canvas.config(yscrollcommand=self.scrollbar.set)
    self.canvas.grid(row=0, column=0, sticky='nsew')
    self.scrollbar.grid(row=0, column=1, sticky='nse')

    self.container.bind('<Configure>', self.handle_scroll)

  def addblock(self):
    self.block = tk.Frame(self.canvas, bd=1, relief='solid')
    self.block.columnconfigure(0, weight=1)
    self.canvas.create_window((0, (self.block_count*25)),
                              window=self.block, anchor="nw",
                              width=200, height=24)
    self.block_count += 1

  def handle_scroll(self, event):
    self.canvas.configure(scrollregion=self.canvas.bbox("all"))

root = tk.Tk()
app = Canvas_Scrollbar_CreateWindow(root)
app.grid(row=0, column=0, sticky='ew')
root.mainloop()

tkinter create_window滚动条

将项目添加到画布时,必须重新配置scrollregion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM