python - Tkinter:如何使用 .after 并在每次通话时重置时间
问题描述
所以基本上我正在尝试制作一个基本的 Tkinter 点击游戏,如果你点击方块的时间太长(准确地说是 2 秒),游戏将结束,但如果你在给定的 2 秒内点击它,方块会改变空间. 但是,除了“2 秒后”之外,我已经弄清楚了,因为我看不到让 .after 做我想做的事情的方法。这是我当前的代码(不工作的 .after 部分也将包括在内)。代码并不完美,但它可以工作。任何关于下一步做什么的建议将不胜感激,因为我已经坚持了一段时间。
import tkinter as tk
from tkinter import *
from random import randint
import time
# variables defined
click = 0
amount = 1
# define root window
root = Tk()
root.title("Clicker Game")
# set canvas properties
width = 400
height = 400
# set properties of rectangle
xtleft = 180
ytleft = 180
xbright = 220
ybright = 220
# invoke canvas
c = Canvas(root, width=width, cursor="plus", height=height, bg='white')
c.pack()
# when square is clicked
def clicked(*args):
c.delete('all')
xpos = randint(1,380)
ypos = randint(1,380)
c.create_polygon(xpos, ypos, xpos+40, ypos, xpos+40, ypos+40, xpos, ypos+40, fill="red", outline = 'blue', tags='clicky')
global click
global amount
click += amount
lbl.configure(text= 'Score: ' + str(click))
root.after(2000, end_game)
# function for starting game
def start_game():
c.delete('all')
clicky = c.create_rectangle(xtleft, ytleft, xbright, ybright, fill="red", outline = 'blue', tags='clicky'),#'changer')
# playtext = c.create_text(150, 50, text="Play", font=("Papyrus", 26), fill='blue', tags='changer')
c.tag_bind("clicky","<Button-1>",clicked)
c.pack()
def end_game():
c.delete('all')
# create frame to put control buttons onto
frame = Frame(root, bg='white', width=400, height=40)
frame.pack(fill='x')
# put button for quitting game
button1 = Button(frame, foreground='red', text='Quit', command=quit)
button1.pack(side='left', padx=10)
# label for click counter
lbl = Label(frame, text="Start Clicking!")
lbl.pack(side='right', padx=10)
# put button for starting game
button2 = Button(frame, foreground='blue', text='Start', command=start_game)
button2.pack(side='bottom', padx=10)
root.mainloop()
解决方案
after
返回一个标识符,可以传递给after_cancel
它以取消作业。
在您的情况下,您需要定义一个全局变量来保存此标识符,然后在开始新作业之前使用它来取消现有作业。
像这样的东西,也许:
after_id = None
def clicked(*args):
global after_id
...
if after_id:
root.after_cancel(after_id)
after_id = root.after(2000, end_game)
推荐阅读
- c# - HL7 - 在 c# 中使用 nHapi 解析样本源 (OBR-15)
- python - 列表理解和处理空列表;列表列表
- javascript - ExtJS:如何在 initComponent 方法中等待 Promise 响应?
- mysql - 编辑另一个表时如何更新一个表的列
- python - 为什么 Asyncio 在 socket.send(data) 中花费时间
- assembly - 为什么我的手臂汇编代码没有在 LLDB 中设置断点
- yii2 - 表的别名
- python - Python 3:在列表中查找项目并据此回答
- css - 如何仅在 3 个面上应用 box-shadow?
- go - mgo 是否具有从查询结果中对每个文档的特定 Slice 字段进行排序的功能?