gpt4 book ai didi

python - 如何在Python中使用tkinter按钮终止两个进程

转载 作者:行者123 更新时间:2023-12-01 00:53:19 35 4
gpt4 key购买 nike

我想用 python 脚本创建两个进程。需要通过 tkinter 按钮启动和停止这些进程。进程正确启动,但无法终止。使用 tkinter 按钮正确终止进程的最简单方法是什么?哪种最佳实践方法?

from tkinter import *
import multiprocessing

def print1():
global a
while a == True:
print('im process 1')

def print2():
global a
while a == True:
print('im process 2')

def start():
process1.start()
process2.start()

def stop():
global a
a = False

a = True

if __name__ == '__main__':

process1 = multiprocessing.Process(target = print1)
process2 = multiprocessing.Process(target = print2)

root = Tk()
root.title("Title")
root.geometry("200x200")

app = Frame(root)
app.grid()

start = Button(app, text="Start", command=start)
stop = Button(app, text="Stop", command=stop)
start.grid()
stop.grid()
root.mainloop()
process1.join()
process2.join()

最佳答案

问题似乎出在 stop 方法中。

我想我可能知道问题是什么,但我不是 100% 确定。为什么的答案似乎在 python 文档中。这里的代码运行良好(我编辑了语法并使用 tkk 作为按钮,它看起来更好):

from tkinter import *
from tkinter import ttk
import multiprocessing


def print1():
global a
while a is True:
print('im process 1')


def print2():
global a
while a is True:
print('im process 2')


def start():
process1.start()
process2.start()


def stop():
process1.kill()
process2.kill()


a = True

if __name__ == '__main__':

process1 = multiprocessing.Process(target=print1)
process2 = multiprocessing.Process(target=print2)

root = Tk()
root.title("Title")
root.geometry("200x200")

app = Frame(root)
app.grid()

start = ttk.Button(app, text="Start", command=start)
stop = ttk.Button(app, text="Stop", command=stop)
start.grid(padx=15, pady=20)
stop.grid(column=1, row=0)
root.mainloop()
process1.join()
process2.join()

希望这有帮助!

关于python - 如何在Python中使用tkinter按钮终止两个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56413663/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com