我正在尝试使用新线程启动一个函数,每次启动该函数时,tkinter应用程序都会再次打开。为了让我看到运行的功能,我需要退出打开的新应用程序,然后启动它。我的代码中是否有一些东西再次调用应用程序并且在启动线程时不允许我的startReceive函数立即运行?
import tkinter as tk
from udpTransfer1 import UdpClass
from threading import Thread
from tkinter import messagebox
import multiprocessing, time, signal
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.alert = ''
self.pack()
self.alive = False
self.create_widgets()
self.c = UdpClass()
self.threadExists= False
self.st = None
def create_widgets(self):
# 1 button
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Save UDP"
self.hi_there["command"] = self.run
self.hi_there.pack(side="top")
# 2 button
self.b2 = tk.Button(self)
self.b2["text"] = "Stop UDP"
self.b2["command"] = self.b2Action
self.b2.pack(side="top")
# 3 button
self.quit = tk.Button(self, text="QUIT", fg="red")
self.quit["command"] = self.kill
self.quit.pack(side="bottom")
def kill(self):
if self.threadExists == True:
# Alert Box
# self.alert = messagebox.showinfo("ALERT").capitalize()
self.alert = messagebox._show(None,'UDP has to be stopped first!')
else:
root.destroy()
def run(self):
# self.st = Thread(target=self.c.startReceive)
# self.st = multiprocessing.Process(target=self.c.startReceive)
self.st = multiprocessing.Process(target=startReceive)
self.st.start()
if (self.st.is_alive()):
print("Thread open")
self.threadExists = True
def b2Action(self):
if self.threadExists:
# self.c.terminate()
terminate()
self.st.terminate()
time.sleep(.1)
if not(self.st.is_alive()):
print("Thread Killed")
self.threadExists = False
else :
self.alert = messagebox._show(None, 'No Detection of UDP Running!')
def startReceive():
print('started')
try:
isRunning = True
# csvfile = open(self.filename, 'w')
# spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
# start_time = time.time()
while isRunning:
print('done')
time.sleep(1)
except:
print('out')
def terminate():
# self.socket.close()
# isRunning = False
print('stopped')
root = tk.Tk()
app = Application(master=root)
app.master.title("UDP Saving")
app.master.geometry('200x200')
app.master.maxsize(200, 500)
app.mainloop()
答案 0 :(得分:0)
不是100%肯定,但这可能是问题所在:
def run(self):
# self.st = Thread(target=self.c.startReceive)
# self.st = multiprocessing.Process(target=self.c.startReceive)
self.st = multiprocessing.Process(target=startReceive)
self.st.start()
if (self.st.is_alive()):
print("Thread open")
self.threadExists = True
我认为您应该将self.threadExists = True
放在之前的if
。
def run(self):
# self.st = Thread(target=self.c.startReceive)
# self.st = multiprocessing.Process(target=self.c.startReceive)
self.st = multiprocessing.Process(target=startReceive)
self.st.start()
if (self.st.is_alive()):
print("Thread open")
self.threadExists = True