Need a way to exit a loop(something like a interrupt) for PySimpleGUI

huangapple go评论59阅读模式
英文:

Need a way to exit a loop(something like a interrupt) for PySimpleGUI

问题

以下是翻译好的代码部分:

我正在尝试编写一个类似于包含的流程图的代码但我在退出最后一个循环时遇到了问题任何帮助都将不胜感激[项目流程图](https://i.stack.imgur.com/bxIbG.jpg)

我们通过在PySimpleGui上定义的按钮启动检测进入最后一个循环我希望能够通过按下定义为停止检测的按钮退出此循环但如果不包括window.read()函数我无法按下停止检测按钮而且我们会进入无限循环如果我包括window.read()函数最后一部分代码将只运行一次而不是所期望的循环

最后一个循环的代码如下

while(1):

        event,values = window.read()
        if event in (None,'Quit'):
            break
        elif event == 'Filter Settings':
            changefitersettings()
        ## 在此处插入项目检测的图像
            print('查看停车场')
        elif event == 'Lot Settings':
            sct_img = sct.grab(bounding_box)
            getcountvalues = changeImage(x,np.array(sct_img))
            Settings()
            print('已按下停车场设置')
            window.close
        elif event =='Start Detection':
            while(1):
                event,values = window.read()
                if event == 'Stop Detection':
                    break
                else:
                    sct_img = sct.grab(bounding_box)
                    videoimage = changeImage(x,np.array(sct_img))
                    #cv.imshow('hello1',videoimage[0])
                    ServerUpdate = UpdateServer(videoimage[1],videoimage[2],videoimage[3],videoimage[4],videoimage[5],videoimage[6],videoimage[7],videoimage[8],videoimage[9],videoimage[10],videoimage[11],videoimage[12])
                    k = cv.waitKey(1) & 0xFF
                    # 按 'q' 键退出
                    if k == ord('q'):
                        break
                cv.destroyAllWindows()

希望这有所帮助!如果您需要进一步的翻译或解释,请告诉我。

英文:

I am trying to write a code that functions like the included flow chart, but I have having issues exiting the last loop. Any help is appreciatedProject Flowchart.

We enter the final loop by pressing the defined button defined as 'Start Detection' on PySimpleGui. I want to be able to exit this loop by pressing a button defined as 'Stop Detection' , but without the window.read() function I cannot press the stop detection button and we are in a endless loop. If i include the window.read function the last bit of code will only run once and not in a loop as desired.

Code for the last loop is here:

while(1):

    event,values = window.read()
    if event in (None,'Quit'):
        break
    elif event == 'Filter Settings':
        changefitersettings()
    ## Put in an image for the item detection in here
        print('View the Parking Lot')
    elif event == 'Lot Settings':
        sct_img = sct.grab(bounding_box)
        getcountvalues = changeImage(x,np.array(sct_img))
        Settings()
        print('Lot Settings has been pressed')
        window.close
    elif event =='Start Detection':
        while(1):
            event,values = window.read()
            if event == 'Stop Detection':
                break
            else:
                sct_img = sct.grab(bounding_box)
                videoimage = changeImage(x,np.array(sct_img))
                #cv.imshow('hello1',videoimage[0])
                ServerUpdate = UpdateServer(videoimage[1],videoimage[2],videoimage[3],videoimage[4],videoimage[5],videoimage[6],videoimage[7],videoimage[8],videoimage[9],videoimage[10],videoimage[11],videoimage[12])
                k = cv.waitKey(1) & 0xFF
                # press 'q' to exit
                if k == ord('q'):
                    break
            cv.destroyAllWindows()

答案1

得分: 1

以下是您要翻译的部分:

"It's better to use multithread if you have another job to do and it take long time."

import time
import datetime
import threading
import PySimpleGUI as sg

def job(window):
    global running
    while running:
        window.write_event_value('Event', datetime.datetime.now().strftime("%H:%M:%S"))
        time.sleep(0.1)

layout = [[sg.Button('Start'), sg.Button('Stop')]]
window = sg.Window('Threading', layout)
running, old = False, None

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSED:
        running = False
        time.sleep(0.5)
        break

    elif event == 'Start' and not running:
        running = True
        window['Start'].update(disabled=True)
        threading.Thread(target=job, args=(window, ), daemon=True).start()

    elif event == 'Stop':
        running = False
        window['Start'].update(disabled=False)

    elif event == 'Event':
        now = values[event]
        if now != old:
            print(now)
            old = now

window.close()

希望这对您有所帮助!

英文:

It's better to use multithread if you have another job to do and it take long time.

Demo code

import time
import datetime
import threading
import PySimpleGUI as sg

def job(window):
    global running
    while running:
        window.write_event_value('Event', datetime.datetime.now().strftime("%H:%M:%S"))
        time.sleep(0.1)

layout = [[sg.Button('Start'), sg.Button('Stop')]]
window = sg.Window('Threading', layout)
running, old = False, None

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSED:
        running = False
        time.sleep(0.5)
        break

    elif event == 'Start' and not running:
        running = True
        window['Start'].update(disabled=True)
        threading.Thread(target=job, args=(window, ), daemon=True).start()

    elif event == 'Stop':
        running = False
        window['Start'].update(disabled=False)

    elif event == 'Event':
        now = values[event]
        if now != old:
            print(now)
            old = now

window.close()

Need a way to exit a loop(something like a interrupt) for PySimpleGUI

答案2

得分: 0

如果我们查看API,我们会看到以下内容:

read

  • Window 类中最重要的方法!这是获取窗口中所有数据的方式。传入一个超时时间(以毫秒为单位)等待最多超时时间毫秒。如果没有其他GUI事件发生,将返回timeout_key。
read(timeout=None,
     timeout_key="__TIMEOUT__",
     close=False)

现在,默认的 window.read() 表示具有无限的超时时间,因此你会看到程序基本上会在等待按键时挂起。但是,timeout 是在返回 timeout_key 给你的 event 变量之前等待的毫秒数,类似于稍后使用 cv.waitKey(1) 时的情况。所以可以使用如下方式:

event, values = window.read(1)

这会给GUI一个机会来读取“Stop Detection”按钮上的鼠标点击事件。

此外,请注意,还有一个名为 window.perform_long_operation() 的方法,可以进行后台处理,这可能是处理这个问题的更整洁的方式?

英文:

If we look at the API we see this:

> read
> * THE biggest deal method in the Window class! This is how you get all of your data from your Window. Pass in a timeout (in milliseconds) to wait for a maximum of timeout milliseconds. Will return timeout_key if no other GUI events happen first.
>
>
> read(timeout = None,
> timeout_key = "__TIMEOUT__",
> close = False)
>

Now, the default window.read() means having an infinite timeout, so you see the program basically hanging waiting for the keypress. However, the timeout is the number of milliseconds to wait before returning the timeout_key to your event variable, similar to later when you use cv.waitKey(1). So use something like this:

event,values = window.read(1)

This gives the GUI a chance to read mouse clicks on the "Stop Detection" button.

Also note that there is a method window.perform_long_operation() that does background processing, which might be a neater way of tackling this?

huangapple
  • 本文由 发表于 2023年4月20日 07:41:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定