问题
My Program uses VLC bindings to play a video while using the time.sleep
function to wait until the video is over before playing the next video. It will play in a loop until the user presses a button and will only exit after that video is completed.
I am using Threading
to handle the video playing as the time.sleep
takes control away from the root
window and the buttons are required to stop the video. Threading solves this.
My only problem is that the video needs to embed in a window. This window acts as an overlay to the main program (which serves an entirely different function) and removes flickering from the video when something updates underneath (this is when embeding the video directly into the root
window.
I know Threading
can't handle any of the GUI stuff that Tkinter
makes, so I have tried to work around it. It works for the most part, it's just when it comes to destroying the window when or before the thread exits I am having trouble.
Below is some example code that opens a window and will then constantly count up and print the result until you tell it to stop (In the actual program it plays videos in the Toplevel
window). There is an additional button to destroy the window. How can I get Destroy
to run via the Thread (instead of the button)? Is it possible?
from tkinter import *
import os
import threading
import time
root = Tk()
class Player(Frame):
def __init__(self, parent=None, **kw):
self.Playing = 0
def Play(self):
self.x = 0
while self.Playing == 1:
print(self.x)
self.x = self.x + 1
time.sleep(3)
if self.Stopping == 1:
self.Playing = 0
sys.exit()
def Go(self):
if self.Playing == 0:
self.Stopping = 0
self.Playing = 1
self.vidcanvas = Toplevel()
self.vidcanvas.configure(bg='black')
self.vidcanvas.geometry('200x200')
self.th1 = threading.Thread(target=self.Play)
self.th1.start()
def Destroy(self):
self.Stopping = 1
self.vidcanvas.destroy()
def Stop(self):
self.Stopping = 1
ply = Player(root)
go = Button(root, text='Play', width=25, command=ply.Go)
go.grid()
stop = Button(root, text='Stop at End of Count', width=25, command=ply.Stop)
stop.grid()
stop = Button(root, text='Kill Window', width=25, command=ply.Destroy)
stop.grid()
root.mainloop()
来源:https://stackoverflow.com/questions/21668538/closing-a-toplevel-window-from-a-seperate-thread-using-threading