我对编程很陌生,刚开始学习一些Python。我认为创建一个像"Typeracer"一样的游戏,但只是尽可能快地键入字母表,这将是一个有趣的挑战。我用Tkinter为它构建了一个GUI。我一开始只是检查用户输入是否等于字符串,然后用下面的代码显示他们赢了:
from tkinter import *
import time
key = "abcdefghijklmnopqrstuvwxyz"
start_time = time.time()
root = Tk()
root.title("ABC Game")
answer = Entry(root, width=50)
answer.grid(row=0, column=0)
def check_answer():
if answer.get() == key:
end_time = time.time()
result_time = round(end_time - start_time, 3)
label_won = Label(root, text="Correct! Your time was: " + str(result_time))
label_won.grid(row=2, column=0)
else:
label_lost = Label(root, text="Incorrect")
label_lost.grid(row=2, column=0)
answer_button = Button(root, text="Submit", command=check_answer)
answer_button.grid(row=1, column=0)
root.mainloop()
但后来我想挑战一下,要求用户输入与字母表中的下一个字母完全相等,不允许出现拼写错误。
我在这一点上有点停滞不前,我的问题是我不知道如何编写只检查用户下一次输入的代码。如果这是预期的输入,那么就这样做,否则就那样做。
from tkinter import *
import time
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
root = Tk()
root.title = "ABC Game"
game_running = False
#This is the part where I'm stuck, might be faults in the code at other places as well
def key_pressed(event):
global pressed_key
pressed_key = repr(event.char)
n_keys_pressed = 0
for letters in alphabet:
while n_keys_pressed <= 28:
if str(pressed_key) == alphabet[n_keys_pressed]:
n_keys_pressed += 1
print("You hit: " + repr(event.char))
def start_game():
global game_running
game_running = True
start_time = time.time
type_frame = Frame(root)
start_button = Button(root, text="Click me to start the timer", width=50, height=10, command=start_game)
start_button.grid(row=0, column=0)
entry = Entry(root, width=50)
entry.grid(row=1, column=0)
root.mainloop()
任何帮助或提示都将不胜感激!谢谢
您需要使用导入时间功能,然后键入time.timer(为计时多少秒(