【问题标题】:Perform multi-threading on a python program在 python 程序上执行多线程
【发布时间】:2020-10-30 20:25:12
【问题描述】:

我想同时执行两个函数, (我是 python 新手,一般是开发) 我试图创建一个我的世界服务器设置助手:

(代码也在开发中)

import os
import tkinter as tk
from tkinter import ttk
import threading
import wget
import json
from pathlib import Path

...


def startndstop(x):
    os.chdir(newpath)
    if x == "start":
        start = str("java" + ram() + namejar + " nogui")
        print("Demarrage du serveur", name, "!")
        os.system(str(start))
    elif x == "stop":
        os.system("stop")

root = tk.Tk()
root.title("Yann Installer")
root.iconbitmap("./minecraft_icon_132202.ico")
root.geometry("640x390")
root.resizable(width=False, height=False)
root.configure(bg="#0f800f")
bgimage = tk.PhotoImage(file="background.gif"))
l = tk.Label(root, image=bgimage)
l.pack()
installbutton = tk.Button(root, text="Installer", command=lambda :threading.Thread(target=install("1.8.3")).start())
installbutton.lift(aboveThis=l)
installbutton.place(x=10, y=10)
startbutton = tk.Button(root, text="Demarrer", command=lambda :threading.Thread(target=startndstop("start")).start())
startbutton.lift(aboveThis=l)
startbutton.place(x=10, y=40)
listeVersion = ttk.Combobox(root, values=versionlist())
listeVersion.current(0)
listeVersion.lift(aboveThis=l)
listeVersion.place(x=80, y=10, width=100)

threading.Thread(target=root.mainloop).start()
threading.Thread(target=startndstop,args=('start',)).start()

但是当我执行脚本时,第二个线程只有在我关闭 tkinter 窗口时才会启动。

编辑:现在函数被正确调用 你能帮帮我吗?

【问题讨论】:

  • 这里没有足够的东西来测试你的问题。
  • @Mike-SMT 我添加了部分代码
  • 你不应该在子线程中运行tkinter.mainloop()。只需为startndstop() 创建线程,然后运行tkinter.mainloop()

标签: python multithreading tkinter


【解决方案1】:

Thread 没有被正确调用。您正在调用root.mainloop() 并将其返回值作为target 传递给线程,要求它运行完成才能返回。相反,通过删除括号将函数对象本身作为目标传递。第二个线程有同样的问题,但需要将参数作为单独的args 元组传递。

使用这个:

threading.Thread(target=root.mainloop).start() # start the tkinter interface
threading.Thread(target=startndstop,args=("start",)).start() # start the minecraft server 

【讨论】:

  • 谢谢,但是 startndstop() 在控制台中运行了一个 minecraft 服务器,Tkinter 无法在其中打印一些它认为的信息,我不知道为什么,当服务器运行时,tkinter窗口没有响应,如果我停止服务器,所有程序都停止...
  • @CalamarRobot 我刚刚更正了您的线程使用情况。你可能有其他问题,但我没有你的完整代码来重现它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 2016-05-17
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多