Python - 我声明了两个参数,但缺少 1 个?



我正在尝试开发一个文本编辑器,用单词替换用户定义的快捷方式。我已经能够解决替换函数并根据我的设计进行调整,但我在处理控制台的语法(见下面的代码(和将信息提供给父窗口时遇到了问题。然而,我一直遇到这个错误,我已经研究了几天如何解决这个问题。它一直在说";replace_shortcut((缺少1个必需的位置参数:"shortcut",但我不确定该怎么办。我在SO上看了其他问题,但没有任何与我的问题相关的问题。(如果有帮助的话,我是Python的新手,从C/C++切换过来(

代码:

from tkinter import *
# For the window
root = Tk()
root.title("Scrypt")
# For the parent text
text = Text(root)
text.pack(expand=1, fill=BOTH)
# For console window and text
win1 = Toplevel()
console_text = Text(win1, width=25, height=25)
console_text.pack(expand=1, fill=BOTH)
# For menubar
menubar = Menu(root)
root.config(menu=menubar)
def get_console_text(*args):
syntax = console_text.get('1.0', 'end-1c')
tokens = syntax.split(" ")
word = tokens[:1]
shortcut = tokens[2:3]
# return word, shortcut
def replace_shortcut(word, shortcut):
idx = '1.0'
while 1:
idx = text.search(shortcut, idx, stopindex=END)
if not idx: break
lastidx = '% s+% dc' % (idx, len(shortcut))
text.delete(idx, lastidx)
text.insert(idx, word)
lastidx = '% s+% dc' % (idx, len(word))
idx = lastidx
def open_console(*args):
replace_shortcut(get_console_text())
win1.mainloop()
# Function calls and key bindings
text.bind("<space>", replace_shortcut) and text.bind("<Return>", replace_shortcut)
win1.bind("<Return>", open_console)
# Menu bar
menubar.add_command(label="Shortcuts", command=open_console)
root.mainloop()

回溯(我想这就是它的名字(:

replace_shortcut() missing 1 required positional argument: 'shortcut'
Stack trace:
>  File "C:UsersKeaton LeesourcereposPyTutorialPyTutorialPyTutorial.py", line 42, in open_console
>    replace_shortcut(get_console_text())
>  File "C:UsersKeaton LeesourcereposPyTutorialPyTutorialPyTutorial.py", line 54, in <module>
>    root.mainloop()

我不确定我是否错过了第二次需要申报的申报,但感谢你们能提供的任何帮助!

您的函数get_console_text()实际上没有返回任何内容,因此当您调用replace_shortcut(get_console_text())时,实际上是在调用replace_shortcut(None)

请注意,在您的get_console_text()函数中,行是:

def get_console_text(*args):
syntax = console_text.get('1.0', 'end-1c')
tokens = syntax.split(" ")
word = tokens[:1]
shortcut = tokens[2:3]
# return word, shortcut   <------ you have commented out the return !!!!

你还需要做:

replace_shortcut(*get_console_text())

请注意*,这条消息告诉Python,在将get_console_text的返回值设置为replace_shortcut作为两个参数之前,需要将其解包为两个参数。

正如其他答案和评论所指出的那样,原因很清楚。还有一点:get_console_text()将返回一个对象None,因此投诉为"0";缺少1个必需的位置参数:"shortcut";,不是两个论点。

最新更新