我创建了一个游戏,它使用tkinter打开GUI。它有一个计时器,当计时器用完时我希望它清除GUI并有一条消息,例如:时间到了,你得分+得分。 我已经能够制作一个在GUI上执行此操作的标签,但即使计时器不为0也只是停留在那里。 这是源代码:
import tkinter
import random
colours = ['Red','Blue','Green','Pink','Black','Yellow','Orange','White','Purple','Brown']
score=0
timeleft=30
def startGame(event):
if timeleft == 30:
countdown()
nextColour()
def nextColour():
global score
global timeleft
if timeleft > 0:
e.focus_set()
if e.get().lower() == colours[1].lower():
score += 1
e.delete(0, tkinter.END)
random.shuffle(colours)
label.config(fg=str(colours[1]), text=str(colours[0]))
scoreLabel.config(text="Score: " + str(score))
def countdown():
global timeleft
if timeleft > 0:
timeleft -= 1
timeLabel.config(text="Time left: " + str(timeleft))
timeLabel.after(1000, countdown)
if timeleft == 0:
canvas.delete("all")
endGame.config(text="Time up, you scored " + str(score))
root = tkinter.Tk()
root.title("TTCANTW")
root.geometry("375x250")
instructions = tkinter.Label(root, text="Type in the colour of the words, and not the word text!", font=('ariel', 12))
instructions.pack()
endGame = tkinter.Label(root, text="Time up, you scored " + str(score), font=('ariel', 12))
endGame.pack()
scoreLabel = tkinter.Label(root, text="Press enter to start", font= ('Helvetica', 12))
scoreLabel.pack()
timeLabel = tkinter.Label(root, text="Time left: " + str(timeleft), font=('Helvetica', 12))
timeLabel.pack()
label = tkinter.Label(root, font=('Helvetica', 60))
label.pack()
e = tkinter.Entry(root)
root.bind('<Return>', startGame)
e.pack()
e.focus_set()
root.mainloop()
提前致谢
答案 0 :(得分:0)
你没有画布小部件,无法删除 你必须使用destroy删除你想要删除的每个小部件.. 我编辑了你的功能
def countdown():
global timeleft
if timeleft > 0:
timeleft -= 1
timeLabel.config(text="Time left: " + str(timeleft))
timeLabel.after(1000, countdown)
if timeleft == 0:
#canvas.delete("all")
instructions.destroy()
timeLabel.destroy()
label.destroy()
e.destroy()
#-------------------------
endGame.config(text="Time up, you scored " + str(score))