pythontkinterpython-turtle

Is there a way to implant tkinter input box into my turtle screen (to create paint)


I have this code taken from trinket.io

import turtle

tina = turtle.Turtle()

tina.shape("turtle")

# promt user for color and make turtle that color
turtle_color = input("What color should tina the turtle be?")

tina.color(turtle_color)

# promt user for background color and makes it that color

myscreen = turtle.Screen()
background_color = input("What color should background be?")
myscreen.bgcolor(background_color)   

What I would like to do is that I would like to merge my tkinter inputbox into one side of the program and create a sort of paint like program

this is the code for tkinter button:

from tkinter import *

master = Tk()
e = Entry(master)
e.pack()

e.focus_set()

def callback():
    print e.get() # This is the text you may want to use later

b = Button(master, text = "OK", width = 10, command = callback)
b.pack()

mainloop()

we could also merge it with the turtle demo program in python which could sort of create paint..

So I just wanted to know how to merge them

by merging I mean the tkinter button and input box in one side of the turtle answer is still accepted.. thank you


Solution

  • Turtle is based on Tkinter, so there is a way to embed other Tkinter widgets to Turtle programs. You can do it in several ways:

    1. go with @cdlane's answer. It is the cleanest one and it uses Turtle's documented interface, specially designed for embedding it in Tkinter apps.
    2. take a look at the second part of @volothud's answer (the first one is described below).
    3. You just need either to specify myscreen._root as a master of a widget or to use myscreen._canvas in another Tkinter window.

    Here is an example for the third option:

    import tkinter as tk
    from tkinter.simpledialog import askstring
    import turtle
    
    
    tina = turtle.Turtle()
    tina.shape("turtle")
    
    screen = turtle.Screen()
    root = screen._root
    
    controls = tk.Frame(root)
    tk.Label(controls, text="Move forward:").pack(side=tk.LEFT)
    fwd_entry = tk.Entry(controls)
    fwd_entry.pack(side=tk.LEFT)
    tk.Button(controls, text="Go!", command=lambda: tina.forward(int(fwd_entry.get()))).pack(side=tk.LEFT)
    controls.pack()
    
    tina_color = askstring("Tina's color", "What color should Tina the turtle be?")
    bg_color = askstring("The background color", "What color should the background be?")
    tina.color(tina_color)
    screen.bgcolor(bg_color)
    
    root.mainloop()
    

    Note 1: why are you using input(...) (which is for terminal/command-line) together with GUI? You can use tkinter.simpledialog instead (see the code snippet above).

    Note 2: Inputs are not validated, so the user can enter anything (you can catch them with try/except and show the error dialog with tkinter.messagebox).