使用turtle您可以使用setPos命令告诉它到某个位置。如果只是将用户输入中的值转换为坐标,请告诉乌龟到那里,然后开始绘制。
这是一个解决方案:
import turtle
from time import sleep
from tkinter import *
#Setup
root=Tk()
wn = turtle.Screen()
wn.bgcolor('black')
player = turtle.Turtle()
player.shape('turtle')
player.color('white')
def goToLocation(coords):
#Get user input and split it into two different coordinants (coordsx and coordsy)
coordsx,coordsy = coords.split(" ")
#Set turtles position to the coords specified
player.hideturtle()
player.penup()
player.setpos(int(coordsx),int(coordsy))
#Draw the circle of size
player.pensize(50)
player.showturtle()
player.pendown()
player.forward(1)
sleep(5)
#Button clicked handler
def retrieve_input():
inputValue=textBox.get("1.0","end-1c")
print(inputValue)
#Calls the previous function
goToLocation(inputValue)
#Input box setup
textBox=Text(root,height=2,width=10)
textBox.pack()
buttonCommit=Button(root,height=1,width=10,text="Commit",command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.pack()
mainloop()
,
将Python turtle与tkinter结合使用时,需要使用 embedded turtle方法,而不是 standalone 您使用的strong>方法。由于海龟是在tkinter之上构建的,因此您实际上已经创建了两个根,最终将遇到麻烦。 (例如,图像可能对您不起作用。)当您同时调用top.mainloop()
和wn.mainloop()
时,组合显然使您感到困惑!
以下是在程序中如何将teminter嵌入乌龟的示例:
import tkinter as tk
from turtle import TurtleScreen,RawTurtle
def set_position():
player.setposition(x_entry.get(),y_entry.get())
player.dot(30,'blue')
player.home()
top = tk.Tk()
canvas = tk.Canvas(top,width=600,height=600)
canvas.pack()
screen = TurtleScreen(canvas)
screen.bgcolor('black')
player = RawTurtle(screen)
player.shape('turtle')
player.color('red','white')
player.penup()
x_entry = tk.DoubleVar()
tk.Label(top,text="X: ").pack(side=tk.LEFT)
tk.Entry(top,textvariable=x_entry).pack(side=tk.LEFT)
y_entry = tk.DoubleVar()
tk.Label(top,text="Y: ").pack(side=tk.LEFT)
tk.Entry(top,textvariable=y_entry).pack(side=tk.LEFT)
tk.Button(top,text="Draw Dot!",command=set_position).pack()
screen.mainloop()
我的建议是:首先,如果可以的话,尝试完全在独立乌龟中工作,除非确实需要,否则不要引入tkinter;第二,不要相信任何会在tkinter环境中尝试使用独立乌龟类嵌入式的错误。
本文链接:https://www.f2er.com/3106100.html