Hung Truong Hung Truong - 4 months ago 22
Python Question

Tkinter : Issue with binding function

I have a project that uses python's turtle module on a canvas, and I'm trying to bind a

<Return>
key to a function that executes the custom commands that I made. This is an example:

from tkinter import *
import turtle
root = Tk()


mainframe=Frame(root)
mainframe.pack(fill=BOTH)
screen = turtle.ScrolledCanvas(mainframe)
tt = turtle.RawTurtle(screen)

def scrollStart(event): #these functions are for scrolling the widget
screen.scan_mark(event.x, event.y)
def scrollDrag(event):
screen.scan_dragto(event.x, event.y, gain = 1)

text = Text(root)
text.pack()

def executeCommand(): #Problem here
def moveForward(pixels):
tt.forward(pixels)



root.bind("<Return>",executeCommand)

root.mainloop()


But when I run it and hit
moveForward(15)
, it says:

TypeError: executeCommand() takes 0 positional arguments but 1 was given

Answer

You need to inject an argument to executeCommand(). So change its definition to:

def executeCommand(event): 
    def moveForward(pixels):
        tt.forward(pixels)