如何从tkinter运行两个并行脚本



有了这段代码,我可以创建一个TK Inter弹出窗口,其中有一个运行Sample_Function的按钮。

这个Sample_Function破坏tk弹出窗口,运行另一个python文件,然后再次打开它自己(第一个弹出窗口(。

我如何运行other_python_file并同时弹出"本身"——这样我就可以在每个函数完成之前触发许多函数?

import sys, os
from tkinter import *
import tkinter as tk
root = Tk()
def Sample_Function():
root.destroy()
sys.path.insert(0,'C:/Data')
import other_python_file
os.system('python this_tk_popup.py')
tk.Button(text='Run Sample_Function', command=Sample_Function).pack(fill=tk.X)
tk.mainloop()

我认为这将达到您想要的效果。它使用subprocess.Popen()而不是os.system()来运行另一个脚本并重新运行弹出窗口,在等待它们完成时不会阻止执行,因此它们现在可以并发执行。

我还添加了一个退出按钮来退出循环。

import subprocess
import sys
from tkinter import *
import tkinter as tk
root = Tk()
def sample_function():
command = f'"{sys.executable}" "other_python_file.py"'
subprocess.Popen(command)  # Run other script - doesn't wait for it to finish.
root.quit()  # Make mainloop() return.
tk.Button(text='Run sample_function', command=sample_function).pack(fill=tk.X)
tk.Button(text='Quit', command=lambda: sys.exit(0)).pack(fill=tk.X)
tk.mainloop()
print('mainloop() returned')
print('restarting this script')
command = f'"{sys.executable}" "{__file__}"'
subprocess.Popen(command)

最新更新