如何从 tkinter 运行两个并行脚本? [英] How to run two parallel scripts from tkinter?
问题描述
使用此代码,我能够创建一个带有按钮的 TK Inter 弹出窗口来运行 Sample_Function
.
With this code I was able to create a TK Inter pop-up with a button to run a Sample_Function
.
这个 Sample_Function
破坏了 tk 弹出窗口,运行另一个 python 文件,然后再次打开它自己(第一个弹出窗口).
This Sample_Function
destroys the tk pop-up, runs another python file, and then opens itself (the first pop-up) again.
我怎样才能同时运行 other_python_file
并弹出本身"——这样我才能在每个函数完成之前触发许多函数?
How can I run the other_python_file
and pop-up 'itself' at the same time — so I can be able to trigger many functions before each one gets completed?
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()
来运行另一个脚本并重新运行在等待它们执行时不会阻止执行的弹出窗口完成,因此它们现在可以并发执行.
I think this will do close to what you want. It uses subprocess.Popen()
instead of os.system()
to run the other script and rerun the pop-up which doesn't block execution while waiting for them to complete, so they can now execute concurrently.
我还添加了一个 Quit 按钮以退出循环.
I also added a Quit button to get out of the loop.
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)
这篇关于如何从 tkinter 运行两个并行脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!