执行第一个if语句(if event.type = KEYDOWN)但第三个 一个人似乎没有。我希望在按下加号键并且字符串变量非空时执行if语句。
from pygame import init, display, font
from pygame.event import get as event_getter
from pygame.locals import *
import time
init()
surf = display.set_mode((400,400))
string =""
num = ['1','2','3','4','5','6','7','8','9','0']
adder = ""
while True:
time.sleep(0.1)
surf.fill((0, )*3)
for event in event_getter():
if event.type == KEYDOWN:
if event.key == K_BACKSPACE:
string = string[:-1]
print("backspace")
if str(event.unicode) in num:
string += str(event.unicode)
print("num")
if event.key == K_PLUS and len(string) >0:
adder = string
string = ""
print(adder)
surf.blit(font.Font(None,50).render(string,1,(255, )*3),(100,100))
display.flip()
答案 0 :(得分:2)
我无法在Windows上使用K_PLUS,因此最好只使用密钥代码。运行下面的代码,当您按下某个键时,您将看到键代码的整数值。 (目前该值设置为61,我相信是英国键盘布局的代码,但似乎45的值适用于其他键盘布局)
from pygame import init, display, font
from pygame.event import get as event_getter
from pygame.locals import *
import time
init()
surf = display.set_mode((400,400))
string =""
num = ['1','2','3','4','5','6','7','8','9','0']
adder = ""
while True:
time.sleep(0.1)
surf.fill((0, )*3)
for event in event_getter():
if event.type == KEYDOWN:
print("Event key: %s" % (event.key))
if event.key == K_BACKSPACE:
string = string[:-1]
print("backspace")
if str(event.unicode) in num:
string += str(event.unicode)
print("num")
if event.key == 61 and len(string) >0:
print("+ pressed")
adder = string
string = ""
print(adder)
surf.blit(font.Font(None,50).render(string,1,(255, )*3),(100,100))
display.flip()
答案 1 :(得分:0)
" shift ="是" +"。
ord(' =')是61
最好如下:
mods = pygame.key.get_mods()
if event.key ==pygame.K_KP_PLUS or (event.key==ord('=') and mods & pygame.KMOD_SHIFT): # "shift =" is "+"
print("+ pressed")