tkinter:在画布上使用滚动条 [英] tkinter: using scrollbars on a canvas

查看:599
本文介绍了tkinter:在画布上使用滚动条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使画布可滚动.但是,一旦我尝试设置可与画布一起使用的滚动条,tkinter似乎就会完全忽略我最初为画布设置的尺寸.我尝试将它们全部包装在一个框架中,设置画布以填充框架,然后设置框架大小,但这会带来相同的问题,除非我也将框架设置为填充窗口,这不是我想要的.基本上,我想要一个固定大小的画布,上面带有滚动条.我当前的代码如下所示(在python 3.1中):

I'm trying to make a canvas scrollable. However, once I try to set up scrollbars to work with the canvas, tkinter seems to completely ignore the dimensions I initially set for my canvas. I've tried packing them all in a frame, setting the canvas to fill the frame and then setting the frame size, but that presents the same problem unless I set the frame to fill the window as well, which isn't what I want. Basically, I want a fixed-size canvas with scrollbars on it. My current code looks like this (in python 3.1):

from tkinter import *
root=Tk()
frame=Frame(root,width=300,height=300)
frame.grid(row=0,column=0)
canvas=Canvas(frame,bg='#FFFFFF',width=300,height=300,scrollregion=(0,0,500,500))
hbar=Scrollbar(canvas,orient=HORIZONTAL)
hbar.pack(side=BOTTOM,fill=X)
hbar.config(command=canvas.xview)
vbar=Scrollbar(canvas,orient=VERTICAL)
vbar.pack(side=RIGHT,fill=Y)
vbar.config(command=canvas.yview)
canvas.config(width=300,height=300)
canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
canvas.pack(side=LEFT,expand=True,fill=BOTH)

root.mainloop()

推荐答案

您的滚动条需要将Frame作为父级,而不是Canvas:

Your scrollbars need to have the Frame as a parent, not the Canvas:

from tkinter import *
root=Tk()
frame=Frame(root,width=300,height=300)
frame.pack(expand=True, fill=BOTH) #.grid(row=0,column=0)
canvas=Canvas(frame,bg='#FFFFFF',width=300,height=300,scrollregion=(0,0,500,500))
hbar=Scrollbar(frame,orient=HORIZONTAL)
hbar.pack(side=BOTTOM,fill=X)
hbar.config(command=canvas.xview)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.pack(side=RIGHT,fill=Y)
vbar.config(command=canvas.yview)
canvas.config(width=300,height=300)
canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
canvas.pack(side=LEFT,expand=True,fill=BOTH)

root.mainloop()

之所以起作用,是因为pack是如何起作用的.默认情况下,它将尝试收缩(或增大)容器以使其完全适合其子容器.因为在原始示例中滚动条是画布的子级,所以画布会缩小以适合.

The reason why this works is due to how pack works. By default it will attempt to shrink (or grow) a container to exactly fit its children. Because the scrollbars are children of the canvas in the original example, the canvas shrinks to fit.

如果您希望滚动条出现在画布内,诀窍是使用额外的框架.将画布和滚动条放置在此内部框架中,关闭边框的边界,然后打开框架的边界.将框架的背景设置为与画布相同,将显示滚动条在画布内.

If you want the scrollbars to appear inside the canvas, the trick is to use an extra frame. Place the canvas and scrollbars in this inner frame, turn the borders off of the canvas and on for the frame. Set the background of the frame to be the same as the canvas and it will appear that the scrollbars are inside the canvas.

这篇关于tkinter:在画布上使用滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆