【问题标题】:Python Program Breaks After 1 RunPython 程序在 1 次运行后中断
【发布时间】:2021-02-10 17:30:23
【问题描述】:

非常感谢您的帮助,感谢你们,现在已经解决了。

问题是在我得到我的 cps 计数后,程序延迟并冻结了。它停止显示cps。

我不知道为什么会发生这种情况或如何解决它。该程序是一个 cps 计数器,它在 1 次尝试后工作,然后如果我第二次使用它就会中断并冻结。

我也不知道代码哪里出错了,非常感谢。

代码如下:

import threading
from tkinter import *
import time

clicks = 0
cps = 0
start = True

wn = Tk()
wn.title("Cps Counter")
wn.geometry("400x300")

def cps5():
    global start
    global cps
    global clicks
    global t1
    start = False
    time.sleep(5)
    cps = (clicks / 5)
    clicks = 0 
    CpsButton.config(text=clicks)
    CpsAmount.config(text=cps)
    start = True
    time.sleep(.1

t1 = threading.Thread(target=cps5)
t1.start()

def AddClicks():
    global clicks
    global start
    clicks += 1
    CpsButton.config(text=clicks)
    if start == True:
        cps5()

CpsButton = Button(wn, text=clicks, command=AddClicks, pady=15, padx=15)
CpsAmount = Label(wn, text=cps, pady=15, padx=15)

CpsAmount.pack()
CpsButton.pack()

wn.mainloop()
    

【问题讨论】:

  • 你需要更具体地说明你在做什么,以及当你说它“breaks”时意味着什么。 minimal reproducible examples 不仅仅是关于代码,它们是关于你如何使用它,你期望在这种情况下发生什么,以及实际上会发生什么(如果有回溯,提供)。
  • 此外,此代码已被破坏(由于其上方未闭合的括号,您将在 t1 = 行周围得到一个 SyntaxError)。像你正在做的那样进行跨线程 tkinter 调用是非常不安全的;使用事件循环来安排它与.after,不要启动线程来调用cps5。并且不要使用time.sleep;整个 GUI 将在睡眠时冻结(同样,这就是 .after 的用途);猜测一下,你认为它是因为time.sleep 而坏掉了,没有意识到当cps5 正在运行时,GUI 会在超过 5 秒的时间内无响应。

标签: python multithreading tkinter


【解决方案1】:
import threading
from tkinter import *
import time

clicks = 0
cps = 0
start = True

wn = Tk()
wn.title("Cps Counter")
wn.geometry("400x300")
clicks = 0
def cps5():
    global start
    global cps
    global clicks
    global t1
    start = False

    CpsButton.config(text=clicks)
    start = True




def AddClicks():
    global clicks
    global start
    clicks += 1
    CpsButton.config(text=clicks)
    if start == True:
        cps5()

CpsButton = Button(wn, text=clicks, command=AddClicks, pady=15, padx=15)
CpsAmount = Label(wn, text=cps, pady=15, padx=15)

CpsAmount.pack()
CpsButton.pack()


def Timer():
    global CpsAmount, cps, clicks
    for i in range(0, 5):
        time.sleep(1)
    cps = (clicks / 5)
    CpsAmount.config(text=cps)
    clicks = 0
    Timer()

t1 = threading.Thread(target=cps5)
t1.start()
t2 = threading.Thread(target=Timer)
t2.start()
wn.mainloop()

我为计数器创建了第二个线程,因为 time.sleep 冻​​结了程序并造成了麻烦。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 2016-01-13
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多