簡體   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