问题:需要在 Tkinter 窗口关闭时完全关闭程序(点击 X)
关闭 Tkinter 窗口时在 paramiko SSH 连接建立之前程序结束。
1- 如果 Paramiko 连接建立,关闭 Tkinter 窗口不会关闭程序。但是输入任何内容并按回车键将关闭程序。
似乎paramiko线程永远不会结束。
如何在连接建立后关闭 paramik 函数线程???我做错了什么???
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import showinfo
from PIL import Image, ImageTk
from tkinter import messagebox
#Paramiko Imports
from paramiko import client
from paramiko.py3compat import input
import concurrent.futures # uses the tHread pool executor
import paramiko
from paramiko.py3compat import u
import threading, sys, traceback
#flag variable
ON = 1
# GUI Function
def gui():
global root
root = Tk()
root.title(" MY Gui")
root.geometry("1050x590")
# Create the canvas
my_canvas = Canvas(root, width=1050, height=590)
my_canvas.pack()
root.protocol("WM_DELETE_WINDOW", on_closing_main)
root.mainloop()
def on_closing_main():
if messagebox.askokcancel("Quit", "Do you want to close the main window?"):
global ON
ON = 0
root.destroy()
def paramik():
# needed parameters for connection
port = 22
hostname = 'beaglebone'
username = 'debian'
password = 'pass'
global chan
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
print("*** Connecting...")
client.connect(hostname, port, username, password)
chan = client.invoke_shell()
print(repr(client.get_transport()))
chan.send('python3 a.py\n')
print("*** SSH Connection to BB_AI stablished!\n")
##########################################################
def writeall(sock):
while True:
data = sock.recv(9999).decode('utf8')
if not data or not ON:
sys.stdout.write("\r\n*** EOF ***\r\n\r\n")
sys.stdout.flush()
chan.close()
client.close()
break
# write to console
print(data, end= '\r', flush= True)
# This exits the program when the Tkinter window is closed as long
# as the connection doesn't go through in paramiko
if not ON:
return 'Exiting'
writer = threading.Thread(target=writeall, args=(chan,))
writer.start()
try:
while True:
d = sys.stdin.read(1)
if not d:
break
# If after paramiko stablishes a connection the Tkinter window
# is closed then the paramik function thread dosnt seem to end so entering
# anthing in console will terminate the Program
# Needed to terminate as soon as the Tkinter window x is clicked!!
if not ON:
return 'Done'
chan.send(d)
except EOFError:
pass
chan.close()
client.close()
def main():
with concurrent.futures.ThreadPoolExecutor() as executor:
t1 = executor.submit(paramik)
print(t1.result(), end= '\r\n', flush=True)
if t1.done():
executor._threads.clear()
concurrent.futures.thread._threads_queues.clear()
sys.exit()
if __name__ == "__main__" : main()
答案 0 :(得分:0)
您可以使用内部布尔变量代替 while True:
中的 def writeall(sock):
,例如 while not self._stop:
。然后,简单地写成def gui():
self._stop = False
root.mainloop()
self._stop = True