[英]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.adb("devices")
其中包含2个self
和"devices"
位置参数
你需要做的是有一个中间方法,如果你想让adb
方法更通用,或者只是将"devices"
放入adb
方法中。
编辑
另请参见: http : //effbot.org/zone/tkinter-callbacks.htm请参阅“将参数传递给回调”部分
编辑2:代码示例
如果你这样做,它应该工作:
button = Button(self.parent, text="Check Device", command=lambda: self.adb("devices"))
然后将您的功能更改为单个*
inlieu **
(关键字arg扩展)请参阅此处: https ://stackoverflow.com/a/36908/6030424以获取更多说明。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.