You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Tkinter+RawTurtle点击拖拽无法绘图的问题?

Turtle+Tkinter绘图应用事件异常问题

我正在用Turtle和Tkinter开发绘图应用。纯Turtle版本中,我实现了点击拖拽自由绘图的功能;但改用RawTurtle并添加Tkinter界面后,出现了异常:点击画布可以移动画笔,拖拽画笔本身可以绘图,但点击拖拽画布区域时仅会移动画笔,无法正常绘图。

纯Turtle版本代码

import turtle
turtle.tracer(False)
turtle.hideturtle()

def draw(x, y):
    t.ondrag(None)
    t.down()
    t.goto(x, y)
    t.up()
    turtle.update()
    t.ondrag(draw)

def move(x, y):
    turtle.onscreenclick(None)
    t.goto(x, y)
    turtle.onscreenclick(move)
    turtle.update()

t = turtle.Turtle()
t.shape("circle")
t.pencolor('black')
t.fillcolor("")
t.up()

t.pensize(6)
t.turtlesize(1000000, 1000000)
ts = turtle.getscreen()
t.ondrag(draw)
turtle.onscreenclick(move)
turtle.update()
turtle.listen()
turtle.done()

Tkinter+RawTurtle版本代码

import tkinter as tk
from functools import partial
from turtle import TurtleScreen, RawTurtle

def draw(x, y):
    turtle.ondrag(None)
    turtle.pendown()
    turtle.goto(x, y)
    turtle.penup()
    screen.update()
    turtle.ondrag(draw)

def move(x, y):
    screen.onclick(None)
    turtle.goto(x, y)
    screen.onclick(move)
    screen.update()

def set_color(color):
    global pen_color
    pen_color = color
    turtle.pencolor(color)
    screen.update()

# --- add widgets ---

root = tk.Tk()

canvas = tk.Canvas(root, width=500, height=500)
canvas.pack(side='right', expand=True, fill='both')

frame = tk.Frame(root)
frame.pack(side='left', fill='y')

tk.Label(frame, text='COLORS').grid(column=0, row=0)

tk.Button(frame, bg='red', width=10, command=partial(set_color, 'red')).grid(column=0, row=1)
tk.Button(frame, bg='yellow', width=10, command=partial(set_color, 'yellow')).grid(column=0, row=2)
tk.Button(frame, bg='green', width=10, command=partial(set_color, 'green')).grid(column=0, row=3)
tk.Button(frame, bg='blue', width=10, command=partial(set_color, 'blue')).grid(column=0, row=4)
tk.Button(frame, bg='black', width=10, command=partial(set_color, 'black')).grid(column=0, row=5)

screen = TurtleScreen(canvas)
screen.tracer(False)

pen_color = 'black'

turtle = RawTurtle(screen)
# turtle.hideturtle()
turtle.shape("circle")
turtle.penup()
turtle.pensize(5)
turtle.color(pen_color, screen.bgcolor())

turtle.ondrag(draw)
screen.onclick(move)
screen.update()
screen.listen()
screen.mainloop()

我刚学Python,猜测问题出在事件监听相关的函数上:纯Turtle版本用turtle.done()维持监听状态,而Tkinter版本用mainloop()后没法再调用done()。我调整过listen、update、done的位置,但程序没有变化。

内容的提问来源于stack exchange,提问作者Percy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:26:02