logo
Tags down

shadow

How do I get turtle to move based on input in Python 3?


By : don fong
Date : October 16 2020, 03:08 PM
will be helpful for those in need Each input() prompts for a new entry from the user.
What your code does is, for every set of 5 entries:
code :
while True:
    entry = input()
    if entry == 'w':
        movemattfd()

    elif entry == 'a':
        movemattlt()

    elif entry == 'd':
        movemattrt()

    elif entry == 's':
        movemattbk()


Share : facebook icon twitter icon

Turtle in python- Trying to get the turtle to move to the mouse click position and print its coordinates


By : FHussain
Date : March 29 2020, 07:55 AM
Hope this helps You are looking for onscreenclick(). It is a method of TurtleScreen. The onclick() method of a Turtle refers to mouse clicks on the turtle itself. Confusingly, the onclick() method of TurtleScreen is the same thing as its onscreenclick() method.
24.5.4.3. Using screen events
code :
>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>>                             # make the turtle move to the clicked point.
>>> screen.onclick(None)        # remove event binding again
screen.onscreenclick(turtle.goto)
def gotoandprint(x, y):
    gotoresult = turtle.goto(x, y)
    print(turtle.xcor(), turtle.ycor())
    return gotoresult

screen.onscreenclick(gotoandprint)
screen.onscreenclick(lambda x, y: turtle.goto(x, y) or print(turtle.xcor(), turtle.ycor())

I'm messing around with the turtle import in python 2.7 with loops and the turtle won't move


By : Anton Pletenev
Date : March 29 2020, 07:55 AM
Does that help Here's a slightly modified version of your code that runs on both Python 2 and Python 3.
code :
import turtle

colors = ["red", "orange", "yellow", "green", "blue", "purple"]
dColors = dict(enumerate(colors))

def circleOfShapes(aTurtle):
    edges = 3
    radius = 100
    for i in range(5):
        for k in range(360 // 5):
            aTurtle.color(dColors.get(i))
            aTurtle.circle(radius, None, edges)
            aTurtle.right(5)
        edges += 1
        radius -= 10

turt = turtle.Turtle()
turt.shape("arrow")
#turt.hideturtle()
#turt.speed(0)

window = turtle.Screen()
window.bgcolor("white")

circleOfShapes(turt)
window.exitonclick()

Python Turtle issue drawing based on user input


By : Rocky Marrone
Date : March 29 2020, 07:55 AM
This might help you I find that beginning programmers either write too much code or too little code. In the case of your tower() function, it's too little code. You also use the x variable for two different purposes -- get out of the habit of using single letter variable names. Your "Please enter number of towers: " question isn't needed as the number of tower heights entered gets you that same value. This is your first logic error:
code :
x = str(h.split(","))
x = map(int, h.split(","))
for x in range (0,n):
    bob.forward(x)
for idx in range(n):
    bob.forward(x[idx])
    ...
from turtle import Turtle, Screen

WIDTH, HEIGHT = 400, 300

def ocean():
    bob.setpos(-WIDTH/2, 0)
    bob.color("midnightblue")
    bob.begin_fill()

    for _ in range(2):
        bob.forward(WIDTH)
        bob.right(90)
        bob.forward(HEIGHT/2)
        bob.right(90)

    bob.end_fill()

def tower():
    for height in heights:
        bob.left(90)
        bob.forward(height)
        bob.right(90)
        bob.forward(50)
        bob.right(90)
        bob.forward(height)
        bob.left(90)

heights_string = input("Please enter height of towers: ")
heights = map(int, heights_string.split(","))

screen = Screen()
screen.setup(width=WIDTH, height=HEIGHT)
screen.bgcolor("orange")

bob = Turtle()

ocean()
tower()

bob.hideturtle()

screen.mainloop()
> python3 test.py
Please enter height of towers: 100,30,140,60,90,20,45

Indefinitely move Python turtle while allowing input


By : user1919476
Date : March 29 2020, 07:55 AM
should help you out An event-driven environment like turtle should never have while True: as it potentially blocks out events (e.g. keyboard). Use an ontimer() event instead.
Generally, onkey() and listen() don't belong in a loop -- for most programs they only need to be called once.
code :
from turtle import Screen, Turtle

def right():
    snake.setheading(0)

def up():
    snake.setheading(90)

def left():
    snake.setheading(180)

def down():
    snake.setheading(270)

def movesnake():

    snake.forward(1)

    screen.ontimer(movesnake, 100)

snake = Turtle("turtle")

screen = Screen()

screen.onkey(right, "Right")
screen.onkey(up, "Up")
screen.onkey(left, "Left")
screen.onkey(down, "Down")

screen.listen()

movesnake()

screen.mainloop()

How do I get the Turtle canvas screen to move with a Turtle module?


By : Kyiv85
Date : March 29 2020, 07:55 AM
like below fixes the issue Below is an example of manipulating the scrolling at the tkinter level to obtain a desired behavior. In this case, I'm keeping the turtle stationary at the center of the screen but using the arrow keys to move the landscape beneath it.
The code between ### Generate a landscape ... and ### Finished generating a ... is from a SO question I answered earlier and is there to make an interesting fractal landscape to explore:
code :
from turtle import Turtle, Screen
from random import random

MAGNIFICATION = 10

def move_left():
    canvas.xview_scroll(-1, "units")
    turtle.setx(turtle.xcor() - MAGNIFICATION)

def move_right():
    canvas.xview_scroll(1, "units")
    turtle.setx(turtle.xcor() + MAGNIFICATION)

def move_up():
    canvas.yview_scroll(-1, "units")
    turtle.sety(turtle.ycor() + MAGNIFICATION)

def move_down():
    canvas.yview_scroll(1, "units")
    turtle.sety(turtle.ycor() - MAGNIFICATION)

screen = Screen()
width, height = screen.screensize()
screen.screensize(width * MAGNIFICATION, height * MAGNIFICATION)

canvas = screen.getcanvas()
canvas.config(xscrollincrement=str(MAGNIFICATION))
canvas.config(yscrollincrement=str(MAGNIFICATION))

# turtle initialization
turtle = Turtle("turtle", visible=False)
turtle.width(MAGNIFICATION)
turtle.resizemode('auto')

### Generate a landscape to explore

screen.tracer(False)

RULES = {'x':'x+yf+', 'y':'-fx-y', 'f':'f', '+':'+', '-':'-'}
sub_string = string = "fx"
LEVEL = 13

for _ in range(LEVEL):

    turtle.pencolor(random(), random(), random())

    for character in sub_string:
        if character == '+':
            turtle.right(90)
        elif character == '-':
            turtle.left(90)
        elif character == 'f':
            turtle.forward(5 * MAGNIFICATION)

    screen.update()

    full_string = "".join(RULES[character] for character in string)
    sub_string = full_string[len(string):]
    string = full_string

screen.tracer(True)

### Finished generating a landscape to explore

turtle.penup()
turtle.home()
turtle.setheading(90)
turtle.color('dark green', 'light green')
turtle.showturtle()

screen.onkey(move_left, "Left")
screen.onkey(move_right, "Right")
screen.onkey(move_up, "Up")
screen.onkey(move_down, "Down")
screen.listen()

screen.mainloop()
Related Posts Related Posts :
  • Add missing rows to data frame equally distribueted
  • Converting text data into Json format
  • TensorFlow: Adding a small noise to pre-trained weights
  • Sudoku solver Python algorithm clarification needed
  • Cant call on list object when generating from a list
  • Accesing elasticsearch on Heroku Bonsai from my computer
  • Oddity calculating runtime with timeit in Python?
  • Create binary array of matching rows in an array using numpy?
  • Pyspark sc.textFile() doesn't load file completely
  • Get/display the author of a post from another app for notifications system
  • Prevent setup.py test / pytest from installing extra dependencies
  • Parse an xml file with python
  • I have a csv which breaks due to extra commas, I require only one column from the dataset but it occurs after the column
  • Pandas query using filter and sort, leading to unresolved errors
  • Execute Highlighted Code in Jupyter notebook Cell?
  • How do I multiply a column in predefined increments?
  • Printing an error message if a user does not input a certain word
  • changing format of a df and removing undesired char
  • Organize data in CSV into multiple lists in Python 3
  • Converting a row of a pandas dataframe into a dataframe itself (instead of a series)?
  • Merge two pandas dataframes with timeseries index
  • How do I achieve this in Folium?
  • Is it possible to change some product's IP address using python scripts? If possible then how ? Includes Printer and oth
  • How to remove margins from Matplotlib bar chart?
  • Procfile Heroku
  • Alternating between upper and lower cases
  • How to remove extra row after set_index() without losing index name?
  • Why is kdeplot scaled off the y-axis when including in Seaborn PairGrid?
  • Converting CSV data to string
  • Failling to build a Django project in VS 2015 - django\contrib\admin\widgets.py
  • How to put lists into one larger list in a certain order for certain conditions? - Python 3.x
  • Sublime uses Python 3, SublimeREPL uses Python 2.7. Huh?
  • Difference between dates in Pandas dataframe
  • python 3: import module
  • Add 2d array to make 3d in python
  • Pandas Merge columns of a pivot table
  • Split dataframe into testing_df and validation_df
  • Python - Splitting words in txt
  • replacing float 0 with NaN
  • What to Use Instead of QWebEngineView for PyQt 5.6 with Anaconda 3
  • Replacement of element in a list of python
  • How to supress 'star imports' warnings from Spyder IDE?
  • What I am doing wrong with S3 PUT request using AWS Signature Version 4
  • How to print the level of every node in binary-tree?
  • What would be equivalent to this list comprehension?
  • Pandas get count of group above group median
  • How to view initialized weights (i.e. before training)?
  • Python - how to split a string list into two?
  • Appending a tuple to a np array returns a list of scalars instead of tuples
  • How to only allow digits, letters, and certain characters in a string in Python?
  • difference between 2 scipy sparse csr matrices
  • How can I use lists in an equation?
  • Save tf.summary.image with Estimator API
  • Plotting multiple stacked bar graph given a pandas dataframe in Python
  • How to print only a certain part of a list?
  • How to resolve ValueError: Input contains NaN, infinity or a value too large for dtype('float64')
  • Missing data in Pandas Merge
  • Python - Get html table element with lxml.html regex
  • Function that would create a copy of lists
  • python 2.7: Debugging an if-else statement (syntax error)
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com