问题
I am trying to draw turtle in canvas and I am also trying to implement zoom in zoom out feature with single click and double click event. When I am not trying to implement tkinter the code works absolutely fine but when I am trying to perform zoom in zoom out feature, I am unable to execute it. I would greatly appreciate any suggestions or help.
Here is my code:
import turtle
import tkinter as tk
from tkinter import *
root = tk.Tk()
canvas = tk.Canvas(master = root, width = 2700, height = 2500)
canvas.pack(fill=BOTH, expand=1)
mb = Menubutton(None, text='Mouse Clicks')
mb.pack()
t = turtle.RawTurtle(canvas)
def parallel():
window= canvas
def zoomin(event):
d = event.delta
if d < 0:
amt=0.9
else:
amt=1.1
canvas.scale(ALL, 2700,2500 , amt,amt)
mb.bind('<Button-1>', zoomin)
def zoomout(event1, d1, amt1):
d1 = event1.delta
if d1 >0:
amt1=1.1
else:
amt1=0.7
canvas.scale(ALL, 2700,2500 , amt, amt)
mb.bind('<Double-1>', zoomout)
t.pu()
t.left(90)
t.forward(70)
t.rt(90)
t.pd()
t.width(8)
t.color("LightGray")
t.forward(1200)
t.back(1200)
t.pu()
t.left(90)
t.forward(25)
t.rt(90)
t.pd()
t.forward(1200)
t.back(1200)
t.pu()
t.setposition(-85, 45)
t.pd()
t.forward(80)
t.left(90)
t.forward(80)
t.left(90)
t.forward(80)
t.left(90)
t.forward(80)
t.left(90)
t.penup()
t.goto(-200, 160)
t.write("Class", True, align="center", font=('TimesNewRoman', 20, 'normal'))
t.pendown()
t.penup()
t.goto(-45, 150)
t.write("1", True, align="center", font=('TimesNewRoman', 50, 'normal'))
t.pendown()
parallel()
t.mainloop()
Thank you.
回答1:
Your program seems incomplete and structured incorrectly. Below is my minimalist example of what I believe you're trying to do. It draws a circle and then lets you use the mouse wheel to zoom it in and out:
import tkinter as tk
from turtle import RawTurtle, TurtleScreen, ScrolledCanvas
def zoom(event):
amount = 0.9 if event.delta < 0 else 1.1
canvas.scale(tk.ALL, 0, 0, amount, amount)
root = tk.Tk()
canvas = ScrolledCanvas(master=root, width=2000, height=2000)
canvas.pack(fill=tk.BOTH, expand=tk.YES)
screen = TurtleScreen(canvas)
turtle = RawTurtle(screen)
turtle.penup()
turtle.sety(-250)
turtle.pendown()
turtle.circle(250)
canvas.bind('<MouseWheel>', zoom)
screen.mainloop()
Note that certain turtle elements, like dot()
and text generated with write()
won't zoom, they'll remain fixed. You'll need to read about the .scale()
method, and go deeper into tkinter, to potentially work around this. Or manually scale your fonts yourself.
来源:https://stackoverflow.com/questions/51050754/implement-python-tkinter-zoom-with-turtle-and-single-double-click