Python Tkinter:使用MouseWheel进行画布滚动 [英] Python Tkinter: Canvas scrolling with MouseWheel
本文介绍了Python Tkinter:使用MouseWheel进行画布滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在Canvas中创建了一棵树,并且还允许MouseWheel上下滚动.
I have created a tree inside a Canvas, and I have also allowed MouseWheel to scroll up and down.
但是,如果树内容未超过画布大小,如何防止滚动? (通过扩展,树内容可能会超出画布大小)
However, how do I prevent scrolling if tree content has not exceed canvas size? (Tree content can possibly exceed canvas size by expanding)
请运行以下代码:
from Tkinter import Tk, Frame, BOTH, Canvas
from xml.dom.minidom import parseString
from idlelib.TreeWidget import TreeItem, TreeNode
class DomTreeItem(TreeItem):
def __init__(self, node):
self.node = node
def GetText(self):
node = self.node
if node.nodeType == node.ELEMENT_NODE:
return node.nodeName
elif node.nodeType == node.TEXT_NODE:
return node.nodeValue
def IsExpandable(self):
node = self.node
return node.hasChildNodes()
def GetSubList(self):
parent = self.node
children = parent.childNodes
prelist = [DomTreeItem(node) for node in children]
itemlist = [item for item in prelist if item.GetText().strip()]
return itemlist
data = '''
<top>
<b>
<c>d</c>
<c>e</c>
</b>
<b>
<c><c><c><c><c>f</c></c></c></c></c>
<c><c><c><c><c>f</c></c></c></c></c>
<c><c><c><c><c>f</c></c></c></c></c>
</b>
</top>
'''
class Application(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background = "white")
parent.configure(bg = "black")
self.pack(fill = BOTH, expand = True, padx = 20, pady = 20)
self.parent = parent
self.parent.geometry('%dx%d+%d+%d' % (700, 700, 0, 0))
self.canvas = Canvas(self, bg = "white", bd = 10, highlightbackground = "black")
self.canvas.grid(column = 0, row = 0, rowspan = 2)
dom = parseString(data)
item = DomTreeItem(dom.documentElement)
node = TreeNode(self.canvas, None, item)
node.update()
node.expand()
self.parent.bind("<MouseWheel>", self.mouse_wheel) # Windows mouse wheel event
self.parent.bind("<Button-4>", self.mouse_wheel) # Linux mouse wheel event (Up)
self.parent.bind("<Button-5>", self.mouse_wheel) # Linux mouse wheel event (Down)
def mouse_wheel(self, event):
""" Mouse wheel as scroll bar """
direction = 0
# respond to Linux or Windows wheel event
if event.num == 5 or event.delta == -120:
direction = 1
if event.num == 4 or event.delta == 120:
direction = -1
self.canvas.yview_scroll(direction, "units")
def main():
root = Tk()
Application(root)
root.mainloop()
if __name__ == '__main__':
main()
推荐答案
您可以使用canvas的bbox
方法检索画布上绘制项目的实际高度. bbox
返回定义一个矩形的元组.您可以将其与画布小部件的高度进行比较.
You can use the bbox
method of canvas to retrieve the actual height of drawn items on canvas. bbox
return a tuple defining a rectangle. You can compare it with the height of your canvas widget.
height = self.canvas.winfo_height()
_,_,_,items_height = self.canvas.bbox(Tkinter.ALL)
if (items_height < height):
direction = 0
这篇关于Python Tkinter:使用MouseWheel进行画布滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文