首页 > 解决方案 > Tkinter 线程问题:system() 最多接受 1 个参数(给定 27 个)

问题描述

我有这个代码来安装 Pygame。

import os
import tkinter as tk
import threading

root = tk.Tk()

canvas1 = tk.Canvas(root, width=300, height=300, bg='gray90', relief='raised')
canvas1.pack()


def run_command(command):
    # for i in range (5):
    threading.Thread(target=os.system, args=f'cmd /c "{command}"').start()  # TypeError: system() takes at most 1
    # argument (27 given)


button1 = tk.Button(text='      Run Command      ', command=lambda: run_command("pip install pygame"), bg='green', fg='white',
                    font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 150, window=button1)

root.mainloop()

但它会引发错误;TypeError: system() 最多接受 1 个参数(给定 27 个)我可以做到os.system(f'cmd /c "{command}"'),但按钮会冻结,所以我不想要那个。如何修复我的错误?

标签: pythonmultithreading

解决方案


import tkinter as tk
import threading

root = tk.Tk()

canvas1 = tk.Canvas(root, width=300, height=300, bg='gray90', relief='raised')
canvas1.pack()


def run_command(command):
    # for i in range (5):
    threading.Thread(target=lambda: os.system(command)).start()


button1 = tk.Button(text='      Run Command      ', command=lambda: run_command("pip install pygame"), bg='green', fg='white',
                    font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 150, window=button1)

root.mainloop()

试试这个,看看。


推荐阅读