为海龟构建内置文本字段,while 语句不起作用
Building a built-in text field for turtle, while statement doesn't work
我构建的文本字段模块有一个问题:为什么 Python IDLE 在 while...break 语句中不起作用?
最初我没有 break 语句,这不起作用,所以我添加了 break 语句,但同样的问题仍然存在。
这是一个很长的脚本。您将需要其中的所有内容。
不要在 repl.it 中 运行,因为它不会 运行。但是它在空闲时 运行。
https://repl.it/@SUPERMECHM500/TextField
如脚本中所述,第 610 行的 while 语句不会在空闲时加载,并且 break
不会按预期工作:如果 TextField.FullOutput 对象具有文字.
我的 None 个问题与 repl.it 有关,所以请不要在您的回答中提及它。
运行 并将此脚本作为来自 python IDLE 的文本文件进行调试。
首先,几个小问题:
def listenforkeys(bool):
bool
是一个Python关键字,选择不同的变量名。 (例如 flag
。)这个 or
并不像你想的那样:
if TextField.FullOutput and TextField.inp != "" or []:
重读 or
。不要将用于 TextField
实现的同一个 turtle 用于 TextField
的实现,如以下语句:
t.clear()
清除 TextField
的用户使用 t
完成的所有操作。使用不同的乌龟。最后,您对 mainloop()
的调用是在错误的地方。一旦您调用它,您的代码就会停止,tkinker 事件处理程序将接管。它通常应该是你的代码des.
的最后一件事
现在正题,这个使用代码:
while TextField.FullOutput == "": #Hope this works with Windows IDLE...
tm.sleep(0.1)
print("Waiting for input...")
if TextField.FullOutput != "":
print('Data sent to RAM.')
break
不要循环等待缓冲区填满。这确实应该是一个事件,但至少是一个回调。我在下面重写了您的代码以使其成为回调,请参阅 Enter()
函数和示例使用代码。它现在可以在 IDLE 和命令提示符下为我工作。我还做了很多其他的小改动,试图稍微清理一下——其中一些可能需要进一步测试...
# Text field that can be used universally.
# Created by SUPERMECHM500 @ repl.it
# Full functionallity can only be achieved by using IDLE on Windows.
from turtle import Screen, Turtle, mainloop
class TextField:
TextFieldBorderColor = '#0019fc'
TextFieldBGColor = '#000000'
TextFieldTextColor = '#ffffff'
ShiftedDigits = {'1':'!', '2':'@', '3':'#', '4':'$', '5':'%', '6':'^', '7':'&', '8':'*', '9':'(', '0':')'}
def __init__(self, callBack=None):
self.callBack = callBack
self.turtle = Turtle(visible=False)
self.turtle.speed('fastest')
self.inp = []
self.FullOutput = ""
self.TextSeparation = 7
self.s = self.TextSeparation
self.key_shiftL = False
def DrawTextField(self, Title):
t = self.turtle
t.pensize(1)
t.color(TextField.TextFieldBorderColor)
t.pu()
t.goto(-200, -190)
t.write(Title)
t.goto(-200, -200)
t.pd()
t.goto(200, -200)
t.goto(200, -250)
t.goto(-200, -250)
t.goto(-200, -200)
t.pu()
t.goto(-200, -225)
t.color(TextField.TextFieldBGColor)
t.pensize(48)
t.pd()
t.forward(400)
t.pu()
t.goto(-190, -220)
t.color(TextField.TextFieldTextColor)
# Defines the function for each defined key.
def ShiftLON(self):
print("Capslock toggled.")
self.key_shiftL = not self.key_shiftL
def Space(self):
self.turtle.write(' ')
self.inp.append(' ')
self.turtle.forward(self.s)
def Backspace(self):
try:
self.inp.pop(-1)
except IndexError:
print("Cannot backspace!")
else:
t = self.turtle
t.pensize(15)
t.color(TextField.TextFieldBGColor)
t.forward(10)
t.backward(self.TextSeparation)
t.shape('square')
t.pd()
t.turtlesize(1.3) # <<< Doesn't work on repl.it
t.stamp()
t.pu()
t.color(TextField.TextFieldTextColor)
t.shape('classic')
t.backward(10)
def Period(self):
if self.key_shiftL:
self.turtle.write('>')
self.inp.append('>')
self.turtle.forward(self.s)
else:
self.turtle.write('.')
self.inp.append('.')
self.turtle.forward(self.s)
def Comma(self):
if self.key_shiftL:
self.turtle.write('<')
self.inp.append('<')
self.turtle.forward(self.s)
else:
self.turtle.write(',')
self.inp.append(',')
self.turtle.forward(self.s)
def Enter(self):
if self.inp != []:
print("Joining input log...")
self.turtle.pu()
self.FullOutput = ''.join(self.inp)
print('joined.')
print(self.FullOutput)
print("Output printed.")
try:
self.callBack(self.FullOutput)
print("Data sent to callback.")
except NameError:
print("No callback defined.")
self.turtle.clear()
print("Display cleared.")
def digit(self, d):
if self.key_shiftL:
d = TextField.ShiftedDigits[d]
self.turtle.write(d)
self.inp.append(d)
self.turtle.forward(self.s)
def letter(self, abc):
if self.key_shiftL:
abc = abc.upper()
self.turtle.write(abc)
self.inp.append(abc)
self.turtle.forward(self.s)
def listenforkeys(self, flag): # Whether or not keys are being used for text field.
s = Screen()
if not flag:
for character in 'abcdefghijklmnopqrstuvwxyz':
s.onkey(None, character)
for digit in '0123456789':
s.onkey(None, digit)
s.onkey(None, 'period')
s.onkey(None, 'comma')
s.onkey(None, 'Shift_L')
# s.onkeyrelease(None, 'Shift_L')
s.onkey(None, 'space')
s.onkey(None, 'BackSpace')
s.onkey(None, 'Return')
if self.FullOutput or self.inp:
self.FullOutput = "" # Reset the text field content
self.inp = [] # Reset input log
print("Stopped listening.")
if flag:
for character in 'abcdefghijklmnopqrstuvwxyz':
s.onkey(lambda abc=character: self.letter(abc), character)
for character in '1234567890':
s.onkey(lambda d=character: self.digit(d), character)
s.onkey(self.Period, 'period')
s.onkey(self.Comma, 'comma')
s.onkey(self.ShiftLON, 'Shift_L')
# s.onkeyrelease(self.ShiftLON, 'Shift_L')
s.onkey(self.Space, 'space')
s.onkey(self.Backspace, 'BackSpace')
s.onkey(self.Enter, 'Return')
s.listen()
print("Listening.")
if __name__ == "__main__":
def text_callback(text):
print("Data received by callback.")
textField.listenforkeys(False)
turtle.pu()
print("Pen up.")
turtle.write(text, align='center', font=('Arial', 30, 'normal'))
print("Text written.")
screen = Screen()
screen.setup(500, 500)
textField = TextField(text_callback)
textField.DrawTextField("Enter Text. Note: Shift is capslock. Capslock disables your keys.")
print("Text field drawn.")
textField.listenforkeys(True)
print("Can type.")
turtle = Turtle(visible=False)
mainloop()
我构建的文本字段模块有一个问题:为什么 Python IDLE 在 while...break 语句中不起作用?
最初我没有 break 语句,这不起作用,所以我添加了 break 语句,但同样的问题仍然存在。
这是一个很长的脚本。您将需要其中的所有内容。 不要在 repl.it 中 运行,因为它不会 运行。但是它在空闲时 运行。
https://repl.it/@SUPERMECHM500/TextField
如脚本中所述,第 610 行的 while 语句不会在空闲时加载,并且 break
不会按预期工作:如果 TextField.FullOutput 对象具有文字.
None 个问题与 repl.it 有关,所以请不要在您的回答中提及它。 运行 并将此脚本作为来自 python IDLE 的文本文件进行调试。
首先,几个小问题:
def listenforkeys(bool):
bool
是一个Python关键字,选择不同的变量名。 (例如 flag
。)这个 or
并不像你想的那样:
if TextField.FullOutput and TextField.inp != "" or []:
重读 or
。不要将用于 TextField
实现的同一个 turtle 用于 TextField
的实现,如以下语句:
t.clear()
清除 TextField
的用户使用 t
完成的所有操作。使用不同的乌龟。最后,您对 mainloop()
的调用是在错误的地方。一旦您调用它,您的代码就会停止,tkinker 事件处理程序将接管。它通常应该是你的代码des.
现在正题,这个使用代码:
while TextField.FullOutput == "": #Hope this works with Windows IDLE...
tm.sleep(0.1)
print("Waiting for input...")
if TextField.FullOutput != "":
print('Data sent to RAM.')
break
不要循环等待缓冲区填满。这确实应该是一个事件,但至少是一个回调。我在下面重写了您的代码以使其成为回调,请参阅 Enter()
函数和示例使用代码。它现在可以在 IDLE 和命令提示符下为我工作。我还做了很多其他的小改动,试图稍微清理一下——其中一些可能需要进一步测试...
# Text field that can be used universally.
# Created by SUPERMECHM500 @ repl.it
# Full functionallity can only be achieved by using IDLE on Windows.
from turtle import Screen, Turtle, mainloop
class TextField:
TextFieldBorderColor = '#0019fc'
TextFieldBGColor = '#000000'
TextFieldTextColor = '#ffffff'
ShiftedDigits = {'1':'!', '2':'@', '3':'#', '4':'$', '5':'%', '6':'^', '7':'&', '8':'*', '9':'(', '0':')'}
def __init__(self, callBack=None):
self.callBack = callBack
self.turtle = Turtle(visible=False)
self.turtle.speed('fastest')
self.inp = []
self.FullOutput = ""
self.TextSeparation = 7
self.s = self.TextSeparation
self.key_shiftL = False
def DrawTextField(self, Title):
t = self.turtle
t.pensize(1)
t.color(TextField.TextFieldBorderColor)
t.pu()
t.goto(-200, -190)
t.write(Title)
t.goto(-200, -200)
t.pd()
t.goto(200, -200)
t.goto(200, -250)
t.goto(-200, -250)
t.goto(-200, -200)
t.pu()
t.goto(-200, -225)
t.color(TextField.TextFieldBGColor)
t.pensize(48)
t.pd()
t.forward(400)
t.pu()
t.goto(-190, -220)
t.color(TextField.TextFieldTextColor)
# Defines the function for each defined key.
def ShiftLON(self):
print("Capslock toggled.")
self.key_shiftL = not self.key_shiftL
def Space(self):
self.turtle.write(' ')
self.inp.append(' ')
self.turtle.forward(self.s)
def Backspace(self):
try:
self.inp.pop(-1)
except IndexError:
print("Cannot backspace!")
else:
t = self.turtle
t.pensize(15)
t.color(TextField.TextFieldBGColor)
t.forward(10)
t.backward(self.TextSeparation)
t.shape('square')
t.pd()
t.turtlesize(1.3) # <<< Doesn't work on repl.it
t.stamp()
t.pu()
t.color(TextField.TextFieldTextColor)
t.shape('classic')
t.backward(10)
def Period(self):
if self.key_shiftL:
self.turtle.write('>')
self.inp.append('>')
self.turtle.forward(self.s)
else:
self.turtle.write('.')
self.inp.append('.')
self.turtle.forward(self.s)
def Comma(self):
if self.key_shiftL:
self.turtle.write('<')
self.inp.append('<')
self.turtle.forward(self.s)
else:
self.turtle.write(',')
self.inp.append(',')
self.turtle.forward(self.s)
def Enter(self):
if self.inp != []:
print("Joining input log...")
self.turtle.pu()
self.FullOutput = ''.join(self.inp)
print('joined.')
print(self.FullOutput)
print("Output printed.")
try:
self.callBack(self.FullOutput)
print("Data sent to callback.")
except NameError:
print("No callback defined.")
self.turtle.clear()
print("Display cleared.")
def digit(self, d):
if self.key_shiftL:
d = TextField.ShiftedDigits[d]
self.turtle.write(d)
self.inp.append(d)
self.turtle.forward(self.s)
def letter(self, abc):
if self.key_shiftL:
abc = abc.upper()
self.turtle.write(abc)
self.inp.append(abc)
self.turtle.forward(self.s)
def listenforkeys(self, flag): # Whether or not keys are being used for text field.
s = Screen()
if not flag:
for character in 'abcdefghijklmnopqrstuvwxyz':
s.onkey(None, character)
for digit in '0123456789':
s.onkey(None, digit)
s.onkey(None, 'period')
s.onkey(None, 'comma')
s.onkey(None, 'Shift_L')
# s.onkeyrelease(None, 'Shift_L')
s.onkey(None, 'space')
s.onkey(None, 'BackSpace')
s.onkey(None, 'Return')
if self.FullOutput or self.inp:
self.FullOutput = "" # Reset the text field content
self.inp = [] # Reset input log
print("Stopped listening.")
if flag:
for character in 'abcdefghijklmnopqrstuvwxyz':
s.onkey(lambda abc=character: self.letter(abc), character)
for character in '1234567890':
s.onkey(lambda d=character: self.digit(d), character)
s.onkey(self.Period, 'period')
s.onkey(self.Comma, 'comma')
s.onkey(self.ShiftLON, 'Shift_L')
# s.onkeyrelease(self.ShiftLON, 'Shift_L')
s.onkey(self.Space, 'space')
s.onkey(self.Backspace, 'BackSpace')
s.onkey(self.Enter, 'Return')
s.listen()
print("Listening.")
if __name__ == "__main__":
def text_callback(text):
print("Data received by callback.")
textField.listenforkeys(False)
turtle.pu()
print("Pen up.")
turtle.write(text, align='center', font=('Arial', 30, 'normal'))
print("Text written.")
screen = Screen()
screen.setup(500, 500)
textField = TextField(text_callback)
textField.DrawTextField("Enter Text. Note: Shift is capslock. Capslock disables your keys.")
print("Text field drawn.")
textField.listenforkeys(True)
print("Can type.")
turtle = Turtle(visible=False)
mainloop()