【问题标题】:Tkinter : Issue with binding functionTkinter:绑定功能问题
【发布时间】:2026-02-22 12:25:01
【问题描述】:

我有一个在画布上使用 python 的 turtle 模块的项目,我正在尝试将 <Return> 键绑定到执行我制作的自定义命令的函数。这是一个例子:

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()

但是当我运行它并点击moveForward(15)时,它会说:

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

【问题讨论】:

    标签: python tkinter command bind


    【解决方案1】:

    您需要向executeCommand() 注入一个参数。所以把它的定义改成:

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

    【讨论】:

    • 非常感谢!忘记了所有关于事件的事情