如何使用 Tkinter 文本输入避免 Python 海龟中的错误颜色字符串错误?

问题描述 投票:0回答:1

我正在开发一个从 tkinter 控制海龟的项目,但是当我尝试更改颜色(更改为红色)时,代码显示这样的错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\acer\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\acer\PycharmProjects\Lesson1\1.py", line 81, in <lambda>
    colourer = Button(text='Colour:', width=15, height=3, command=lambda: colour_change(colour, pen))
  File "C:\Users\acer\PycharmProjects\Lesson1\1.py", line 49, in colour_change
    feather.color(new_color)
  File "C:\Users\acer\AppData\Local\Programs\Python\Python39\lib\turtle.py", line 2217, in color
    pcolor = self._colorstr(pcolor)
  File "C:\Users\acer\AppData\Local\Programs\Python\Python39\lib\turtle.py", line 2697, in _colorstr
    return self.screen._colorstr(args)
  File "C:\Users\acer\AppData\Local\Programs\Python\Python39\lib\turtle.py", line 1159, in _colorstr
    raise TurtleGraphicsError("bad color string: %s" % str(color))
turtle.TurtleGraphicsError: bad color string: red

这是代码(首先编写颜色,然后保存更改并单击“颜色”):

import turtle
from tkinter import *

# Windows created
control = Tk()
pen = turtle.Turtle()
# A bit of design
# Button size: 15 = 115 px, 1 = 7 and 2/3 px
pen.shape('turtle')
control.title('Turtle controller v1.0')
control.geometry('345x168')
colour = ""


def colour_change(new_color, feather, hexa=False, rgb=False):
    if hexa is True:
        feather.color('#%s' % new_color)
    elif rgb is True:
        feather.colormode(255)
        feather.color(new_color)
    else:
        feather.color(new_color)


def changecolour():
    global colour
    colour = colourin.get(1.0, END)


colourer = Button(text='Colour', width=15, height=3, command=lambda: colour_change(colour, pen))
colourer.place(x=0, y=112)
colourin = Text(width=15, height=3)
colourin.place(x=115, y=112)
colourconv = Button(text='Save change', width=15, height=3, command=changecolour)
colourconv.place(x=230, y=112)
# Window mainloop
turtle.mainloop()
control.mainloop()

我尝试输入红色、红色和“红色”,但都不起作用。我尝试自己调试 - 从 Tkinter 的传输工作正常,但海龟不接受该字符串。

python tkinter turtle-graphics python-turtle
1个回答
2
投票

问题很微妙。要调试此问题,请使用

repr()
:

检查字符串
colour = colourin.get(1.0, END)
print(repr(colour))

你会看到这个打印:

'red\n'

现在问题很清楚了:有一个尾随换行符。剥掉它:

colour = colourin.get(1.0, END).strip()

评论中指出,您也可以稍微改进您的 Tkinter 代码。

1.0
不是正确的文本索引 - 更喜欢
"1.0"

"end-1c"
而不是
END
将跳过最后一个字符,但无论如何我仍然会
.strip()
,因为用户可能添加了任意空格。其他验证和清理可能是必要的,具体取决于您希望如何处理错误输入。

© www.soinside.com 2019 - 2024. All rights reserved.