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

Python 如何从tkinter运行两个并行脚本?,python,tkinter,tk,Python,Tkinter,Tk,有了这段代码,我可以创建一个TK Inter弹出窗口,其中有一个按钮可以运行Sample\u函数 此Sample_函数将销毁tk弹出窗口,运行另一个python文件,然后再次打开自身(第一个弹出窗口) 如何运行other_python_文件并同时弹出“自身”——这样我就可以在每个函数完成之前触发许多函数 import sys, os from tkinter import * import tkinter as tk root = Tk() def Sample_Function():

有了这段代码,我可以创建一个TK Inter弹出窗口,其中有一个按钮可以运行
Sample\u函数

Sample_函数
将销毁tk弹出窗口,运行另一个python文件,然后再次打开自身(第一个弹出窗口)

如何运行
other_python_文件
并同时弹出“自身”——这样我就可以在每个函数完成之前触发许多函数

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)

你的代码是如何工作的?我希望它在运行opther_python_文件时打开os.system('python this_tk_popup.py')。现在它正在等待opther_python_文件结束运行这个_tk_popup.pyTry将
root.destory()
替换为
root.quit()
。运行“other_python_文件”时仍然没有运行“this_tk_popup”。但这一次,“第一个弹出窗口”仍在运行,但没有响应
root.quit()
应该会导致当前运行的
mainloop()
退出。您可能必须首先执行
root.destory()
,以使其窗口在未自动关闭时消失。导入其他python文件与运行脚本不是一回事,在不知道它的作用的情况下,很难预测下面的
os.system()
调用是否会执行。