gpt4 book ai didi

python - Tkinter:如何使用箭头键滚动整个 Canvas ?

转载 作者:行者123 更新时间:2023-11-30 23:04:31 24 4
gpt4 key购买 nike

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

我很难理解如何仅使用箭头键(键盘上、下、左、右)实现整个 Canvas 的滚动。

救命!

最佳答案

xviewyview Canvas 的方法用于滚动 Canvas 。这些方法与将滚动条连接到 Canvas 所用的方法完全相同。您可以按“单位”或“页数”滚动。 “单位”由 Canvas 选项 xscrollincrement 定义和yscrollincrement .

您要绑定(bind)的事件是 <Up> , <Down> , <Left><Right> .

将它们放在一起,您将创建如下所示的绑定(bind):

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"))

您需要确保 Canvas 具有焦点。您可以显式地为其提供焦点,但您可能还希望单击鼠标来将焦点提供给 Canvas :

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()

关于python - Tkinter:如何使用箭头键滚动整个 Canvas ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33665542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com