I'm trying to develop a text editor that replaces user-defined shortcuts with words. I've been able to solve the replace function and tweak it to my design, but I'm having trouble taking the syntax of the console (see code below) and feeding the information to the parent window. However, I keep running into this error and I've been working for a couple days on how to fix this. It keeps saying "replace_shortcut() missing 1 required positional argument: 'shortcut'", but I'm not sure what I'm supposed to do. I've looked on other questions on SO, but nothing that's relevant to my problem. (If it helps I'm new to Python, switched over from C/C++)
Code:
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()
The traceback (I think that's what it's called):
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()
I'm not sure if I'm missing a second declaration that needs to be, well, declared, but any help you guys can offer is appreciated!
your function get_console_text()
doesn't actually return anything, so when you call replace_shortcut(get_console_text())
, you are effectively calling replace_shortcut(None)
Notice in your get_console_text()
function the lines are :
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 !!!!
You also need to do :
replace_shortcut(*get_console_text())
Note the *
, this tells Python that the return value from get_console_text
needs to be unpacked into two arguments before being set to replace_shortcut as two arguments.