问题描述
我正在尝试开发一个文本编辑器,用文字替换用户定义的快捷方式。我已经能够解决替换功能并将其调整到我的设计中,但是我无法使用控制台的语法(请参阅下面的代码)并将信息提供给父窗口。但是,我一直遇到这个错误,我已经研究了几天来解决这个问题。它一直说“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:\Users\Keaton Lee\source\repos\PyTutorial\PyTutorial\PyTutorial.py",line 42,in open_console
> replace_shortcut(get_console_text())
> File "C:\Users\Keaton Lee\source\repos\PyTutorial\PyTutorial\PyTutorial.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
,因此投诉是“缺少 1 个必需的位置参数:'shortcut'”,而不是两个参数。