Python Turtle Window on Top - python

When I run the code below using Idle for Python 3.6, the turtle screen appears underneath the Idle screens, which is very unsatisfying.
If I omit the input request for the background colour and just use wn.bgcolor("blue") the window appears at the front, as I want.
I've looked at the docs and found turtle.setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"]) but there doesn't appear to be any kind of z-index parameter.
Any suggestions please?
import turtle
bg_colour = input("Enter the desired background colour: ")
wn = turtle.Screen()
wn.bgcolor(bg_colour) # Set the window background color
wn.title("Hello, Tess!") # Set the window title
tess = turtle.Turtle()
tess.color("blue") # Tell tess to change her color
tess.pensize(3) # Tell tess to set her pen width
tess.forward(50)
tess.left(120)
tess.forward(50)
wn.mainloop()

You could give the following a try -- the rootwindow.call() tkinter incantations are from the turtle demo code where they move the turtle graphics window above the terminal window:
from turtle import Turtle, Screen
bg_colour = input("Enter the desired background colour: ")
wn = Screen()
rootwindow = wn.getcanvas().winfo_toplevel()
rootwindow.call('wm', 'attributes', '.', '-topmost', '1')
rootwindow.call('wm', 'attributes', '.', '-topmost', '0')
wn.bgcolor(bg_colour) # Set the window background color
wn.title("Hello, Tess!") # Set the window title
tess = Turtle()
tess.color("blue") # Tell tess to change her color
tess.pensize(3) # Tell tess to set her pen width
tess.forward(50)
tess.left(120)
tess.forward(50)
wn.mainloop()

Related

Text input on a Turtle based Python Game

I am trying to create a turtle based, text adventure game with an interactive GUI. But I ran into a problem. In the image attached, you will see a ">" and then after that, I would like the user to be able to type a command, and submit it to determine the path of a game. I am relatively new to python, so I am not familiar with external libraries or modules that could help with this.
import os
import turtle
#SCREEN
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Untitled Game")
#Box
box = turtle.Turtle()
box.color("white")
box.speed(0)
box.penup()
box.setposition(-500, -200)
box.pensize(5)
box.pendown()
box.fd(900)
#TEXT IN TEXT BOX
text = turtle.Turtle()
text.speed(0)
text.color("white")
text.penup()
text.setposition(-350, 300)
text.write("This is a test", False, align="left", font=("Helvetica", 25, "normal"))
text.hideturtle()
#TEXT ARROW
arrow = turtle.Turtle()
arrow.speed(0)
arrow.color("white")
arrow.penup()
arrow.setposition(-360, -300)
arrow.pendown()
arrow.pensize(4)
arrow.write(">", False, align="left", font=("Helvetica", 60, "normal"))
screen.mainloop()
What it looks like right now

Limit the min/max of pensize() in turtle

The pen size stays the same size when I press the - and + keys, as I draw with turtle.
I reworked the problem using some plausible answers, but to no avail. I looked on the internet for a similar solution and came up empty-handed.
import turtle
turtle.setup(400,500) # Determine the window size
wn = turtle.Screen() # Get a reference to the window
wn.title("Handling keypresses!") # Change the window title
wn.bgcolor("lightgreen") # Set the background color
tess = turtle.Turtle() # Create our favorite turtle
# The next four functions are our "event handlers".
def h1():
tess.forward(30)
def h2():
tess.left(45)
def h3():
tess.right(45)
def h4():
tess.color("red")
def h5():
tess.color("green")
def h6():
tess.color("blue")
def h7():
tess.pensize(0)
def h8():
tess.pensize(20)
def h9():
wn.bye() # Close down the turtle window
def h10():
tess.backward(30)
# These lines "wire up" keypresses to the handlers we've defined.
wn.onkey(h1, "Up")
wn.onkey(h2, "Left")
wn.onkey(h3, "Right")
wn.onkey(h4, "r")
wn.onkey(h5, "g")
wn.onkey(h6, "b")
wn.onkey(h7, "-")
wn.onkey(h8, "+")
wn.onkey(h9, "q")
wn.onkey(h10, "Down")
# Now we need to tell the window to start listening for events,
# If any of the keys that we're monitoring is pressed, its
# handler will be called.
wn.listen()
wn.mainloop()
I'm trying to use the .pensize() method in turtle to increase/decrease its thickness between a restricted range of 0 and 20 using the - and + keys by function with the .onkey() method. Any help is appreciated.
You don't need a global variable to track the pen size. Turtles are already (effectively) global entities and know their own pen size (tested code):
def h7():
pensize = tess.pensize() - 1
if pensize >= 0:
tess.pensize(pensize)
def h8():
pensize = tess.pensize() + 1
if pensize <= 20:
tess.pensize(pensize)
However, there's another issue that will keep this, or any solution, from working correctly. This code:
wn.onkey(h7, "-")
wn.onkey(h8, "+")
Needs to instead be:
wn.onkey(h7, "minus")
wn.onkey(h8, "plus")
Otherwise, the "-" symbol will cause all unassigned keys (including shift key needed to type "+") to invoke the h7() handler! This change should also allow the equivalent keys on the keypad to work. Complete code:
from turtle import Screen, Turtle
wn = Screen() # Get a reference to the window
wn.setup(400, 500) # Determine the window size
wn.title("Handling keypresses!") # Change the window title
wn.bgcolor("lightgreen") # Set the background color
tess = Turtle() # Create our favorite turtle
# The next nine functions are our "event handlers".
def h1():
tess.forward(30)
def h2():
tess.left(45)
def h3():
tess.right(45)
def h4():
tess.color("red")
def h5():
tess.color("green")
def h6():
tess.color("blue")
def h7():
pensize = tess.pensize() - 1
if pensize >= 0:
tess.pensize(pensize)
def h8():
pensize = tess.pensize() + 1
if pensize <= 20:
tess.pensize(pensize)
def h9():
tess.backward(30)
# These lines "wire up" keypresses to the handlers we've defined.
wn.onkey(h1, "Up")
wn.onkey(h2, "Left")
wn.onkey(h3, "Right")
wn.onkey(h4, "r")
wn.onkey(h5, "g")
wn.onkey(h6, "b")
wn.onkey(h7, "minus")
wn.onkey(h8, "plus")
wn.onkey(h9, "Down")
wn.onkey(wn.bye, "q") # Close down the turtle window
# Now we need to tell the window to start listening for events,
# If any of the keys that we're monitoring is pressed, its
# handler will be called.
wn.listen()
wn.mainloop()

Turtle in Tkinter creating multiple windows

I am attempting to create a quick turtle display using Tkinter, but some odd things are happening.
First two turtle windows are being created, (one blank, one with the turtles), secondly, any attempt of turning the tracer off is not working.
This might be a simple fix but at the moment I cannot find it.
Any help would be appreciated,
Below is the code:
import tkinter as tk
import turtle
window = tk.Tk()
window.title('Top 10\'s')
def loadingscreen():
canvas = tk.Canvas(master = window, width = 500, height = 500)
canvas.pack()
arc1 = turtle.RawTurtle(canvas)
arc2 = turtle.RawTurtle(canvas)
#clean up the turtles and release the window
def cleanup():
turtle.tracer(True)
arc1.ht()
arc2.ht()
turtle.done()
#animate the turtles
def moveTurtles(rangevar,radius,extent,decrease):
for distance in range(rangevar):
arc1.circle(-radius,extent = extent)
arc2.circle(-radius,extent = extent)
radius -= decrease
#Set the turtle
def setTurtle(turt,x,y,heading,pensize,color):
turt.pu()
turt.goto(x,y)
turt.pd()
turt.seth(heading)
turt.pensize(pensize)
turt.pencolor(color)
#draw on the canvas
def draw():
#set variables
rangevar = 200
radius = 200
decrease = 1
extent = 2
#setup and draw the outline
turtle.tracer(False)
setTurtle(arc1,0,200,0,40,'grey')
setTurtle(arc2,14,-165,180,40,'grey')
moveTurtles(rangevar,radius,extent,decrease)
#setup and animate the logo
turtle.tracer(True)
setTurtle(arc1,0,200,0,20,'black')
setTurtle(arc2,14,-165,180,20,'black')
moveTurtles(rangevar,radius,extent,decrease)
#main program
def main():
turtle.tracer(False)
arc1.speed(0)
arc2.speed(0)
draw()
cleanup()
if __name__ == "__main__":
try:
main()
except:
print("An error occurred!!")
loadingscreen()
Essentially I am creating a Tk window, then a canvas, then two turtles, and then animating these turtles
My guess is you're trying to call turtle screen methods without actually having a turtle screen. When turtle is embedded in tkinter like this, you can overlay a Canvas with a TurtleScreen instance which will provide some, but not all, of the screen features of the standalone turtle:
import tkinter as tk
from turtle import RawTurtle, TurtleScreen
def cleanup():
""" hide the turtles """
arc1.hideturtle()
arc2.hideturtle()
def moveTurtles(rangevar, radius, extent, decrease):
""" animate the turtles """
for _ in range(rangevar):
arc1.circle(-radius, extent=extent)
arc2.circle(-radius, extent=extent)
radius -= decrease
def setTurtle(turtle, x, y, heading, pensize, color):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.setheading(heading)
turtle.pensize(pensize)
turtle.pencolor(color)
def draw():
# set variables
rangevar = 200
radius = 200
decrease = 1
extent = 2
screen.tracer(False) # turn off animation while drawing outline
# setup and draw the outline
setTurtle(arc1, 0, 200, 0, 40, 'grey')
setTurtle(arc2, 14, -165, 180, 40, 'grey')
moveTurtles(rangevar, radius, extent, decrease)
screen.tracer(True) # turn animation back on for the following
# setup and animate the logo
setTurtle(arc1, 0, 200, 0, 20, 'black')
setTurtle(arc2, 14, -165, 180, 20, 'black')
moveTurtles(rangevar, radius, extent, decrease)
# main program
window = tk.Tk()
window.title("Top 10's")
canvas = tk.Canvas(master=window, width=500, height=500)
canvas.pack()
screen = TurtleScreen(canvas)
arc1 = RawTurtle(screen)
arc1.speed('fastest')
arc2 = RawTurtle(screen)
arc2.speed('fastest')
draw()
cleanup()
Another suggestion: don't mess with tracer() until after everything else is working and then (re)read it's documentation carefully.
I just have the answer for the two windows that are being created: the one with the turtles is obvious, and the blank one is for the main root window that you define (window = tk.Tk()). If you want it not to appear at all, you can add the following line right after its definition:
window.withdraw()
I found this solution here and here.

How do I get data from tkinter and add it into turtle?

I've been trying to tkinters .Entry command and use the user input to put into turtle, but I keep getting an error:
In my case, I am trying to ask the user for a color that they want to use in turtle.
My code:
import tkinter
from turtle import Turtle
#Create and Format window
w = tkinter.Tk()
w.title("Getting To Know You")
w.geometry("400x200")
#Favorite Color
lbl3= tkinter.Label(w, text = "What's your favorite color?")
lbl3.grid(row = 10 , column = 2)
olor = tkinter.Entry(w)
olor.grid(row = 12, column = 2)
t = Turtle()
t.begin_fill()
t.color(olor)
shape = int (input ("What is your favorite shape?"))
w.mainloop()
My recommendation is you work within turtle completely and not drop down to the tkinter level:
from turtle import Turtle, Screen
# Create and Format window
screen = Screen()
screen.setup(400, 200)
screen.title("Getting To Know You")
# Favorite Color
color = screen.textinput("Choose a color", "What's your favorite color?")
turtle = Turtle()
turtle.color(color)
turtle.begin_fill()
turtle.circle(25)
turtle.end_fill()
turtle.hideturtle()
screen.mainloop()
If you must do this from tkinter, you need to read more about tkinter elements like Entry to know their capabilities. You also need to read more about turtle as it is invoked differently when embedded inside of a tkinter window. Here's a rough approximation of what you're trying to do:
import tkinter as tk
from turtle import RawTurtle, TurtleScreen, ScrolledCanvas
root = tk.Tk()
root.geometry("400x200")
root.title("Getting To Know You")
def draw_circle():
turtle.color(color_entry.get())
turtle.begin_fill()
turtle.circle(25)
turtle.end_fill()
# Favorite Color
tk.Label(root, text="What's your favorite color?").pack()
color_entry = tk.Entry(root)
color_entry.pack()
tk.Button(root, text='Draw Circle', command=draw_circle).pack()
canvas = ScrolledCanvas(root)
canvas.pack(fill=tk.BOTH, expand=tk.YES)
screen = TurtleScreen(canvas)
turtle = RawTurtle(screen, visible=False)
screen.mainloop()

How to change the background color of RawTurtle

I wrote a python script, which should open a Tkinter window with a canvas and let turtle draw in this canvas. Now I want to change the background color of the canvas, but it stays always white (default settings of RawTurtle?). Is there any possibility to draw on a background with another color?
from Tkinter import *
import turtle
root = Tk()
root.overrideredirect(1)
ccanvas = Canvas(root, width = 800, height = 480)
ccanvas.pack()
turtle = turtle.RawTurtle(ccanvas)
turtle = turtle.bgcolor("black")
mainloop()
If I try turtle = turtle.bgcolor("black") the error looks like this: 'RawTurtle' object has no attribute 'bgcolor'.
You can supply a turtle.TurtleScreen (provides a bgcolor method) to turtle.RawTurtle instead of directly using Canvas :
ccanvas = Canvas(root, width = 800, height = 480)
turtle_screen = turtle.TurtleScreen(ccanvas)
turtle_screen.bgcolor("black")
ccanvas.pack()
turtle = turtle.RawTurtle(turtle_screen)
ccanvas.configure(background='black')

Categories

Resources