【问题标题】:Changing canvas scroll region on Python turtle canvas更改 Python 乌龟画布上的画布滚动区域
【发布时间】:2015-08-05 02:15:03
【问题描述】:

我可以更改 Python 乌龟画布上的滚动区域吗?我希望绘图随之移动,而不仅仅是坐标移动。我想要的外观是类似横向滚动条的,屏幕的显示区域移动到屏幕上的海龟中心。

我尝试过使用turtle.setworldcoordinates(llx, lly, urx, ury),但是,从文档中,“这执行了screen.reset()”。我也看过 this SO question ,但这涉及滚动条,不会轻易使海龟居中,并且画布空间有限。我正在寻找的是:

  • 将显示区域移动到海龟的中心
  • 同时移动绘图
  • 具有无限滚动区域
  • 不显示滚动条
  • 可以用函数快速调用 我最好的猜测是能够以某种方式拥有无限滚动的画布,然后隐藏滚动条并根据海龟位置设置它们。

这在 Python 2.7 中可行吗?我不介意它是否也使用 tkinter。

编辑:6-3-15

我找到了canvas.xviewcanvas.yview 函数,但是一旦我定义了screen = turtle.TurtleScreen(canvas),它们似乎就不起作用了,而且TurtleScreen 没有xviewyview 函数。我似乎无法完成这项工作。

然后我找到了turtle.ScrolledCanvas()。这似乎很理想,只是它没有从程序手动设置滚动的方法。我可以在turtle.ScrolledCanvas()上手动设置滚动吗???

【问题讨论】:

    标签: python-2.7 tkinter turtle-graphics


    【解决方案1】:

    使用 canvas.place() 方法无需重置即可更改画布的位置。它也会移动海龟和图纸,所以每次移动后都需要重新定位海龟。

    接下来的代码用左右箭头移动画布并用空格画一个圆圈,同时让乌龟保持在中心。不需要 ScrolledCanvas,只需一个非常大的标准画布:

    import turtle
    import Tkinter as tk
    
    
    def keypress(event):
        global xx, canvas, t, speed
        ev = event.keysym
        if ev == 'Left':
            xx += speed
        else:
            xx -= speed
    
        canvas.place(x=xx)
        t.setposition((-canvas.winfo_width() / 4) - (xx + 250), 0)
        return None
    
    
    def drawCircle(_):
        global t
        t.pendown()
        t.fillcolor(0, 0, 1.0)
        t.fill(True)
        t.circle(100)
        t.fill(False)
        t.fillcolor(0, 1, 0)
        t.penup()
    
    # Set the main window
    window = tk.Tk()
    window.geometry('500x500')
    window.resizable(False, False)
    
    # Create the canvas. Width is larger than window
    canvas = turtle.Canvas(window, width=2000, height=500)
    xx = -500
    canvas.place(x=xx, y=0)
    
    # Bring the turtle
    t = turtle.RawTurtle(canvas)
    t.shape('turtle')  # nicer look
    t.speed(0)
    t.penup()
    t.setposition((-canvas.winfo_width() / 4) - (xx + 250), 0)
    
    # key binding
    window.bind('<KeyPress-Left>', keypress)
    window.bind('<KeyPress-Right>', keypress)
    window.bind('<KeyPress-space>', drawCircle)
    
    drawCircle(None)
    speed = 3  # scrolling speed
    window.mainloop()
    

    真正的无限滚动需要每次使用所需的偏移量重新绘制画布中的每个项目,而不是实际移动或滚动画布。 create_image() 之类的函数可以在静态背景下产生运动的错觉,但它会重置绘图。

    【讨论】:

      猜你喜欢
      • 2013-10-30
      • 1970-01-01
      • 2016-11-27
      • 1970-01-01
      • 2019-01-15
      • 2016-07-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      相关资源
      最近更新 更多