Trying To Take User Input And Make A Turtle Dot
Solution 1:
When using Python turtle in conjunction with tkinter, you need to use the embedded turtle methods, not the standalone methods you used. As turtle is built atop tkinter, you've effectively created two roots and will eventually run into trouble. (E.g. images probably won't work for you.) You're clearly confused by the combination as you call both top.mainloop()
and wn.mainloop()
!
Here's an example of how to embed turtle in tkinter for your program:
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()
My recommendations are: first, try to work completely within standalone turtle if you can, and not introduce tkinter unless you really need to; second, don't trust any answer that makes this same mistake of trying to use standalone turtle classes embedded in a tkinter environment.
Solution 2:
with turtle you can tell it to go to a position using setPos commands. If you just convert the values from your user input into coordinates, tell you turtle to go there and then start drawing.
Here is a solution:
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')
defgoToLocation(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 handlerdefretrieve_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()
Post a Comment for "Trying To Take User Input And Make A Turtle Dot"