所以,我想在Pygame中创建一个用户文本输入框,并告诉我看一个名为inputbox的类模块。因此,我下载了inputbox.py并导入了我的主游戏文件。然后,我在其中运行了一个函数,并收到一个错误:
Traceback (most recent call last):
File "C:\Users\Dennis\Tournament\inputbox.py", line 64, in <module>
if __name__ == '__main__': main()
File "C:\Users\Dennis\Tournament\inputbox.py", line 62, in main
print(ask(screen, "Name") + " was entered")
File "C:\Users\Dennis\Tournament\inputbox.py", line 46, in ask
display_box(screen, question + ": " + string.join(current_string,""))
AttributeError: 'module' object has no attribute 'join'
我尝试独自运行inputbox.py并收到相同的错误。我正在使用Python 3.3和Pygame 3.3,所以可能是一个问题。有人告诉我最近删除了许多“字符串”函数。如果有人知道问题所在并可以解决,则代码如下:如果有人能够解决问题,我将不胜感激,因为我一直在尝试在我的Pygame游戏中设置用户输入。非常感谢您提前提供答案。
# by Timothy Downs, inputbox written for my map editor
# This program needs a little cleaning up
# It ignores the shift key
# And, for reasons of my own, this program converts "-" to "_"
# A program to get user input, allowing backspace etc
# shown in a box in the middle of the screen
# Called by:
# import inputbox
# answer = inputbox.ask(screen, "Your name")
#
# Only near the center of the screen is blitted to
import pygame, pygame.font, pygame.event, pygame.draw, string
from pygame.locals import *
def get_key():
while 1:
event = pygame.event.poll()
if event.type == KEYDOWN:
return event.key
else:
pass
def display_box(screen, message):
"Print a message in a box in the middle of the screen"
fontobject = pygame.font.Font(None,18)
pygame.draw.rect(screen, (0,0,0),
((screen.get_width() / 2) - 100,
(screen.get_height() / 2) - 10,
200,20), 0)
pygame.draw.rect(screen, (255,255,255),
((screen.get_width() / 2) - 102,
(screen.get_height() / 2) - 12,
204,24), 1)
if len(message) != 0:
screen.blit(fontobject.render(message, 1, (255,255,255)),
((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10))
pygame.display.flip()
def ask(screen, question):
"ask(screen, question) -> answer"
pygame.font.init()
current_string = []
display_box(screen, question + ": " + string.join(current_string,""))
while 1:
inkey = get_key()
if inkey == K_BACKSPACE:
current_string = current_string[0:-1]
elif inkey == K_RETURN:
break
elif inkey == K_MINUS:
current_string.append("_")
elif inkey <= 127:
current_string.append(chr(inkey))
display_box(screen, question + ": " + string.join(current_string,""))
return string.join(current_string,"")
def main():
screen = pygame.display.set_mode((320,240))
print(ask(screen, "Name") + " was entered")
if __name__ == '__main__': main()
当您应该从str对象中使用它时,您正在尝试从字符串模块中使用join方法。
string.join(current_string,"")
例如该行应为
"".join(current_string)
其中current_string是可迭代的。
只是有关.join方法如何工作的简单示例
", ".join(['a','b','c'])
将为您提供字母a b和c的str对象,并用逗号和空格分隔。
[string.join(words[, sep])
has been deprecated with Python 2.4
,已用Python 2.4
完全删除
直到Python 3.0
,一个人都可以同时使用Python 2.7
和string.join(words[, sep])
(尽管自sep.join(words)
起不建议使用第一个,而从Python 2.4
起只有后者可用。