Python-通过单击tkinter终止程序?

时间:2018-07-24 11:07:30

标签: python tkinter while-loop

我正在尝试从tkinter窗口按钮终止一个简单的while循环,但在这里我无法这样做:

Recorder.py

from PIL import ImageGrab
import numpy as np
import cv2
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)

def record_screen():

    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter('ResultFile.avi', fourcc, 25.0, screensize)

    while True:
        try:
            img = ImageGrab.grab()
            img_np = np.array(img)
            frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
            out.write(frame)
            print('recording....')
        except KeyboardInterrupt:
            break

    out.release()
    cv2.destroyAllWindows()

# uncomment when running as main
#record_screen()

这是tkinter代码

from tkinter import *
import Recorder

class Trial:

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        # self.printButton = Button(frame, text="Print Message", command=self.printMessage)
        # self.printButton.pack(side=LEFT)
        self.recorderButton = Button(frame, text="Start Recording", command=Recorder.record_screen)
        self.recorderButton.pack(side=LEFT)

        self.quitButton = Button(frame, text="Quit Recording", command=root.destroy)
        self.quitButton.pack(side=LEFT)

    # same freezing problem with method approach
    # def quitFunction(self):
    #     root.destroy()

    # def printMessage(self):
    #    print("Hello .....")

root = Tk()
alpha = Trial(root)
root.mainloop()

问题在于,当我简单地单击“退出”按钮时,tk代码会按预期执行操作,但是,在录制开始的那一刻,它会创建一个无限循环,我认为这会阻止“退出”按钮终止窗口

0 个答案:

没有答案