gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:16 26 4
gpt4 key购买 nike

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

采用 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"))

然后将您的函数更改为单个 * 代替 **(关键字 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)

关于python - 采用 1 个位置参数,但给出了 2 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37791744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com