0

I am creating a gui for my ML project but I am unable to successfully create a vertical scrollbar that actually works. Here's my code

import tkinter as  tk
import tkinter.filedialog
from PIL import ImageTk, Image

class App:
  def __init__(self, master):
   

    frame = tk.Frame(master,width=500,height=500)
    frame.pack()
    self.canvas=tk.Canvas(frame,width=500, height=500,borderwidth=0,highlightthickness=0,background='white',scrollregion=(0,0,500,800))
    self.canvas.pack()
    vbar=tk.Scrollbar(self.canvas,orient="vertical")
    vbar.pack(side="right",fill="y")
    vbar.config(command=self.canvas.yview)
    self.canvas.config(yscrollcommand=vbar.set)
    self.canvas.bind("<Configure>",lambda e:self.canvas.configure(scrollregion=self.canvas.bbox('all'))) 
    root.minsize(500,500)
    


    self.button = tk.Button(self.canvas, 
                         text="QUIT", fg="red",
                         command=frame.quit)
    self.button.pack()
    
    self.button2 = tk.Button(self.canvas,
                         text="Display image",
                         command=self.Display_image)
    self.button2.pack()
    
  def Display_image(self):
    
    f = tkinter.filedialog.askopenfilename(
        parent=root, initialdir='D:/Test',
        title='Choose file',
        filetypes=[('bmp images', '.bmp')]
        )        
    image = ImageTk.PhotoImage(Image.open(f))
    l1 = tkinter.Label(self.canvas, image=image)
    l1.image = image
    l1.pack()
root = tk.Tk()
app = App(root)
root.mainloop()

The code does create a scrollbar but is not functional. However when I include this line of code self.canvas.create_rectangle((0,0,500,800)) in the code the rectangle scrolls.

  • You should use .`.create_image(...)` instead of image in a label. – acw1668 May 07 '21 at 10:23
  • You shouldn't use `.pack`/`.grid`/`.place` when a widget's parent is a `` object – TheLizzard May 07 '21 at 10:33
  • If you want a scrollable frame, look at [this](https://stackoverflow.com/a/66215091/11106801) – TheLizzard May 07 '21 at 10:34
  • @TheLizzard thanks a lot, i was able to create app. can you explain to me why i shouldn't use `.pack`? – Shifan Abbas May 08 '21 at 05:47
  • @ShifanAbbas `tkinter` has `tkinter.Frame` which is supposed to be like a container where you can `.pack`/`.grid`/`.place` widgets. On the other hand `tkinter.Canvas` is supposed to be for drawing shapes and moving sprites around. It does support placing widgets inside it but not with the `.pack`/`.grid`/`.place` but with `.create_window(, window=)` – TheLizzard May 08 '21 at 08:56

0 Answers0