用乌龟和单/双击实现Python tkinter缩放

时间:2018-06-26 20:15:36

标签: python python-3.x turtle-graphics

我正在尝试在画布上绘制海龟,并且还尝试通过单击和双击事件来实现放大缩小功能。当我不尝试实现tkinter时,代码可以正常工作,但是当我尝试执行放大功能时,我将无法执行。我将不胜感激任何建议或帮助。

这是我的代码:

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

谢谢。

1 个答案:

答案 0 :(得分:0)

您的程序似乎不完整且结构不正确。以下是我认为您正在尝试做的最简单的例子。它会画一个圆,然后让您使用鼠标滚轮放大和缩小它:

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

请注意,某些乌龟元素(例如dot()和使用write()生成的文本不会缩放,它们将保持不变。您需要阅读有关.scale()方法的知识,并深入研究tkinter,以解决此问题。或自己手动缩放字体。