繁体   English   中英

Tkinter:如何使用。在每次通话后重置时间

[英]Tkinter: How to use .after and have the time reset with each call

所以基本上我正在尝试制作一个基本的 Tkinter 点击游戏,如果你花太长时间点击方块(准确地说是 2 秒),游戏将结束,但如果你在给定的 2 秒内点击它,方块会改变空间. 但是,除了“2 秒后”之外,我已经弄清楚了,因为我看不到 get.after 做我想做的事情的方法。 这是我当前的代码(也将包括 non working.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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM