简体   繁体   中英

Python Tkinter - How to contain a widget within a Canvas?

I'm trying to put an image inside the Canvas that has the same width as the Canvas but the height is according to the aspect ratio, and using a Scrollbar to scroll the same. Here's the relevant part of the code.

#Canvas and Scrollbar
img_canvas = Canvas(main_frame, height = height, width = width+15)
vsb = Scrollbar(img_canvas, orient = 'vertical')
vsb.pack(side = 'right', fill = 'y')
vsb.configure(command = img_canvas.yview)
canvas.config(yscrollcommand = vsb.set)
text.window_create("end", window = img_canvas)
text.insert("end", "\n")

#Insert Image into the Canvas
im = Image.open(str(opath)+"//Ques_"+str(temp)+".png")
w, h = im.size
im = im.resize((width, int((h/w)*width)), Image.ANTIALIAS)
img = ImageTk.PhotoImage(im)
ques = Label(img_canvas, image = img)
ques.image = img
ques.pack(side = 'left', expand = False)

The problem I am encountering is that the image expands completely in y , and hence can't be scrolled. I want to contain the part of the image that fits into the Canvas 's dimensions and the rest can be scrolled.

You have to use create_image to put an image on a canvas and have it be scrollable. You can't use pack or place or grid . You don't need to put the image in a label first, unless you specifically want it to be a label with a border. In that case, you need to use create_window to add the label to the canvas.

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