我用Python做了一个小游戏,随机地有一个图片改变位置,玩家应该点击图片来获得积分。然而,我想在游戏中设置一个计时器,这样用户就只有例如10秒的时间。
我真的无法让它与mainloop一起工作。
在这段代码中,
checker
方法只运行一次,
rpl
方法是游戏方法。
import tkinter as tk
import random
import time
point=0
root=tk.Tk()
root.title("Game 2")
root.geometry("450x400")
root.resizable(0,0)
img = tk.PhotoImage(file="dice\\1.png")
canvas = tk.Canvas(root, width=100, height=100)
# canvas.place(x=400,y=100,anchor='center')
canvas.create_image(50,50,image=img,anchor='center')
bt1=tk.Button(text="Start",width=10)
bt1.place(x=0,y=0,anchor=tk.NW)
lbl1=tk.Label(root,text="Score: "+str( point),font=('robot',20))
lbl1.place(x=10,y=370,anchor=tk.W)
lbl2=tk.Label(root,text="Time: "+str(st-en),font=('robot',20))
lbl2.place(x=150,y=370,anchor=tk.W)
def rpl(event):
global st
global point
point+=1
lbl1.configure(text="Score: "+str( point))
canvas.place(x=random.randint(75,350),y=random.randint(75,300),anchor='center')
def start():
global st
st=time.perf_counter()
print("START !")
canvas.place(x=random.randint(75, 350), y=random.randint(75, 300), anchor='center')
def checker():
total=time.perf_counter()-st
lbl2.configure(text="Time: " +str(int(total)))
if(total>=10):
print ("Game over")
canvas.configure(width=0,height=0)
lblend=tk.Label(root,text="Game over\nYou got "+str(point)+" Points")
lblend.configure(font=('robot',20),fg='Red')
lblend.place(x=225,y=200,anchor='center')
checker()
canvas.bind('<Button-1>',rpl)
bt1.configure(command=start)
tk.mainloop()