[英]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.