Tkinter:如何使用箭头键滚动整个画布?

时间:2015-11-12 06:26:52

标签: python tkinter tkinter-canvas

我正在编写一个使用Tkinter的python应用程序,它的画布用于从调色板中绘制图表。图表可能会变得非常大,我目前正在使用鼠标按钮(ButtonPress-1)来按住并拖动整个画布。

我很难理解如何使用箭头键(键盘向上,向下,向左和向右)实现整个画布的滚动。

帮助!

1 个答案:

答案 0 :(得分:3)

画布的xviewyview方法用于滚动画布。这些是用于将滚动条连接到画布的方法。您可以按“单位”或“页面”滚动。 “单位”由画布选项xscrollincrementyscrollincrement定义。

您要绑定的事件包括<Up><Down><Left><Right>

将它们放在一起,您将创建看起来像这样的绑定:

self.canvas.bind("<Left>",  lambda event: self.canvas.xview_scroll(-1, "units"))
self.canvas.bind("<Right>", lambda event: self.canvas.xview_scroll( 1, "units"))
self.canvas.bind("<Up>",    lambda event: self.canvas.yview_scroll(-1, "units"))
self.canvas.bind("<Down>",  lambda event: self.canvas.yview_scroll( 1, "units"))

您需要确保画布具有焦点。您可以明确地将焦点放在焦点上,但您可能还需要单击鼠标来将焦点放在画布上:

self.canvas.focus_set()
self.canvas.bind("<1>", lambda event: self.canvas.focus_set())

这是一个完整的工作示例:

import Tkinter as tk
import random

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.canvas = tk.Canvas(self, background="bisque")
        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.hsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
        self.canvas.configure(xscrollcommand=self.hsb.set, yscrollcommand=self.vsb.set)

        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.vsb.grid(row=0, column=1, sticky="ns")
        self.hsb.grid(row=1, column=0, sticky="ew")

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        for i in range(100):
            x = random.randint(0, 1000)
            y = random.randint(0, 1000)
            width = random.randint(10, 50)
            height = random.randint(10, 50)
            fill = random.choice(("red", "orange", "yellow", "green", "blue", "violet"))
            self.canvas.create_rectangle(x, y, x+width, y+height, fill=fill)

        self.canvas.configure(scrollregion = self.canvas.bbox("all"))

        self.canvas.bind("<1>",     lambda event: self.canvas.focus_set())
        self.canvas.bind("<Left>",  lambda event: self.canvas.xview_scroll(-1, "units"))
        self.canvas.bind("<Right>", lambda event: self.canvas.xview_scroll( 1, "units"))
        self.canvas.bind("<Up>",    lambda event: self.canvas.yview_scroll(-1, "units"))
        self.canvas.bind("<Down>",  lambda event: self.canvas.yview_scroll( 1, "units"))

        self.canvas.focus_set()

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()