首页 > 解决方案 > 如何从 tkinter 获取数据并将其添加到海龟中?

问题描述

我一直在尝试使用 tkinters .Entry 命令并使用用户输入将其放入海龟,但我一直收到错误消息:

就我而言,我试图向用户询问他们想在海龟中使用的颜色。

我的代码:

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()

标签: pythontkinterturtle-graphics

解决方案


我的建议是你完全在 turtle 内工作,而不是下降到 tkinter 级别:

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()

如果您必须从 tkinter 执行此操作,则需要阅读有关 tkinter 元素的更多信息,例如Entry了解它们的功能。您还需要阅读有关 turtle 的更多信息,因为它在嵌入 tkinter 窗口时以不同方式调用。这是您尝试执行的操作的粗略近似值:

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()

推荐阅读