采用 1 个位置参数,但给出了 2 个

takes 1 positional argument but 2 were given

我想 运行 一个命令行工具 运行 在一个单独的函数中,并传递给按钮单击此程序的附加命令,但每次我都会收到此作为响应。

接受 1 个位置参数,但给出了 2 个

from tkinter import *
import subprocess


class StdoutRedirector(object):
    def __init__(self,text_widget):
        self.text_space = text_widget

    def write(self,string):
        self.text_space.insert('end', string)
        self.text_space.see('end')

class CoreGUI(object):
    def __init__(self,parent):
        self.parent = parent
        self.InitUI()

        button = Button(self.parent, text="Check Device", command= self.adb("devices"))
        button.grid(column=0, row=0, columnspan=1)

    def InitUI(self):
        self.text_box = Text(self.parent, wrap='word', height = 6, width=50)
        self.text_box.grid(column=0, row=10, columnspan = 2, sticky='NSWE', padx=5, pady=5)
        sys.stdout = StdoutRedirector(self.text_box)

    def adb(self, **args):
        process = subprocess.Popen(['adb.exe', args], stdout=subprocess.PIPE, shell=True)
        print(process.communicate())
        #return x.communicate(stdout)


root = Tk()
gui = CoreGUI(root)
root.mainloop()

错误

Traceback (most recent call last):
  File "C:/Users/Maik/PycharmProjects/Lernen/subprocessExtra.py", line 33, in <module>
    gui = CoreGUI(root)
  File "C:/Users/Maik/PycharmProjects/Lernen/subprocessExtra.py", line 18, in __init__
    button = Button(self.parent, text="Check Device", command= self.adb("devices"))
TypeError: adb() takes 1 positional argument but 2 were given
Exception ignored in: <__main__.StdoutRedirector object at 0x013531B0>
AttributeError: 'StdoutRedirector' object has no attribute 'flush'

Process finished with exit code 1

有人能帮帮我吗

**args 有问题

这是因为你在这里提供了一个位置参数:

button = Button(self.parent, text="Check Device", command= self.adb("devices"))

命令需要一个回调函数。并且您将 adb 方法的响应传递给它。 (更多信息请看这里:http://effbot.org/tkinterbook/button.htm

当调用该行时,正在调用 self.adb("devices")。 如果您查看 adb

的定义
def adb(self, **args):

你只要求 1 个位置参数 self 和任意数量的关键字参数 **args 然后你用 self 的 2 个位置参数调用它 self.adb("devices")"devices"

你需要做的是有一个中间方法,如果你想让 adb 方法更通用,或者只是把 "devices" 放到 adb 方法中。

编辑

另请参阅此处:http://effbot.org/zone/tkinter-callbacks.htm 请参阅 "Passing Argument to Callbacks"

部分

编辑 2:代码示例

如果你这样做,它应该有效:

button = Button(self.parent, text="Check Device", command=lambda:  self.adb("devices"))

然后将您的函数更改为单个 * 代替 **(关键字 arg 扩展)请参阅此处: 了解更多说明。

def adb(self, *args):
    process = subprocess.Popen(['adb.exe', args], stdout=subprocess.PIPE, shell=True)
    print(process.communicate())
    #return x.communicate(stdout)

问题在于您声明 args 的方式:它应该是 *args(一个星号)而不是 **args(两个星号)。一个星号指定任意数量的位置参数,其中两个星号表示任意数量的命名参数。

此外,您需要将 args 正确传递给 adb.exe:

def adb(self, *args):
    process = subprocess.Popen(['adb.exe'] + args, stdout=subprocess.PIPE, shell=True)