簡體   English   中英

函數正好接受2個參數(給定4個)

[英]Function takes exactly 2 arguments (4 given)

我試圖在樹莓派上運行一些python代碼,以模擬不同的傳感器。 當兩次調用一個函數時,被告知我提供了太多參數。 我將有大約20個不同的函數都調用此outputPWM函數,但是我僅以兩個函數為例。

我本周才開始使用python,所以我不太確定如何解決此問題。 如果我可以在下一次調用之前以某種方式清除參數的outputPWM函數,否則我的代碼可能存在一些基本缺陷

def outputPWM(n1,i):
    num1 = (n1.get()) 
    result = int(num1)
    dutycycle = result 
    print(List[25])
    List[i].start(0)
    List[i].ChangeDutyCycle(dutycycle)
    print("Duty cycle is %d" % dutycycle)
    print("output is on port %d" %i)

def control():
    ControlReturn = tk.StringVar()  
    ControlLabel = tk.Label(master, text="Control Return Air Temperature (Degrees Celcius)").grid(row=0, column=0)  
    ControlResult = tk.Label(master)  
    ControlEntry = tk.Entry(master, textvariable=ControlReturn).grid(row=0,column=2)
    global outputPWM
    outputPWM=partial(outputPWM,ControlReturn,20)  
    buttonCal = tk.Button(master, text="Enter", command=outputPWM).grid(row=0, column=3) 

def display():   
    DisplayReturn = tk.StringVar()  
    DisplayLabel = tk.Label(master,text="Display Return Air Temperature (Degrees Celcius)").grid(row=1, column=0)  
    DisplayEntry = tk.Entry(master, textvariable=DisplayReturn).grid(row=1,column=2)
    global outputPWM
    outputPWM= partial(outputPWM,DisplayReturn,25)
    buttonCal = tk.Button(master, text="Enter", command=outputPWM).grid(row=1, column=3)

display()
control()

我收到的錯誤是:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1550, in __call__
    return self.func(*args)
TypeError: outputPWM() takes exactly 2 arguments (4 given)

無論在哪里創建局部函數,都應為其命名,而不是全局outputPWM:

global outputPWM
outputPWM_ = partial(outputPWM, ControlReturn, 20)
buttonCal = tk.Button(master, text="Enter", command=outputPWM_).grid(row=0, column=3)

該代碼執行兩次,第一次在display() ,第二次在control() (參數稍有不同,但這無關緊要)

global outputPWM
outputPWM=partial(outputPWM,ControlReturn,20)

它將原始函數替換為派生的部分函數,​​該函數添加了2個args。 第二輪用從第一部分函數派生的另一個部分函數替換該部分函數。 結果函數分兩步添加2 + 2 args。 這就是“需要2個參數(給定4個)”錯誤的來源。

解決方案不是重復使用相同的名稱(請參閱https://en.wikipedia.org/wiki/Variable_shadowing ),並且除非確實沒有必要,否則不使用global

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM