캔버스가 내장 된 마우스 스크롤을 지원 (캔버스의 각 요소를 이동 아니라 캔버스의 표시 영역을 스크롤하지 않음). 전자는 마우스를 클릭 한 위치를 기억하고, 마우스는 마우스로 마우스를 클릭했을 때 적절한 크기의 픽셀을 스크롤합니다.
참고 : gain
속성은 scan_moveto
에 마우스가 움직이는 각 픽셀에 대해 이동할 픽셀 수를 알려줍니다. 기본적으로 10입니다. 커서와 캔버스 사이에 1 : 1 상관 관계가 필요하면이 값을 1로 설정해야합니다 (예제와 같이).
여기 예입니다 :
import Tkinter as tk
import random
class Example(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
self.canvas = tk.Canvas(self, width=400, height=400, background="bisque")
self.xsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
self.ysb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set)
self.canvas.configure(scrollregion=(0,0,1000,1000))
self.xsb.grid(row=1, column=0, sticky="ew")
self.ysb.grid(row=0, column=1, sticky="ns")
self.canvas.grid(row=0, column=0, sticky="nsew")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
for n in range(50):
x0 = random.randint(0, 900)
y0 = random.randint(50, 900)
x1 = x0 + random.randint(50, 100)
y1 = y0 + random.randint(50,100)
color = ("red", "orange", "yellow", "green", "blue")[random.randint(0,4)]
self.canvas.create_rectangle(x0,y0,x1,y1, outline="black", fill=color)
self.canvas.create_text(50,10, anchor="nw",
text="Click and drag to move the canvas")
# This is what enables scrolling with the mouse:
self.canvas.bind("<ButtonPress-1>", self.scroll_start)
self.canvas.bind("<B1-Motion>", self.scroll_move)
def scroll_start(self, event):
self.canvas.scan_mark(event.x, event.y)
def scroll_move(self, event):
self.canvas.scan_dragto(event.x, event.y, gain=1)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
너무 감사합니다, 내가 필요 정확히입니다! 무한 (또는 거의 무한) 캔버스를 가질 수 있으므로 오른쪽/왼쪽/위/아래로 원하는만큼 스크롤 할 수 있습니다. – Basj
@Basj : 실제 한계가 문서화되지 않았지만 나는 그것이 무한하다고 생각하지 않습니다. 스크롤 영역을 더 크게 만들어 실험 해보십시오. 내 생각 엔 좌표는 32 비트 정수입니다. –
이 스크롤 코드 @BryanOakley에 다시 한 번 감사드립니다. "확대/축소"의 경우'canvas.scale'과 같은 것을 사용할 것입니까? 나는 확대/축소 할 때 처음부터 직접 구현하여 구현했지만,'tkinter'에 내장 된 것이있을 것이라고 생각합니까? – Basj