TypeError:exe()缺少1个必需的位置参数:“self”

2024-10-02 00:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这个网站上有很多关于这个问题的答案,但是我遇到的所有解决方案似乎对我的情况没有帮助。我正在用Tkinter(并试图学习如何使用它)来制作一个游戏。我想要一个按钮(退出游戏)退出Tkinter窗口,但我一直得到这个错误:

TypeError: exe() missing 1 required positional argument: 'self'

我的代码:

from tkinter import *
import sys as s, time as t

try: color = sys.stdout.shell
except AttributeError: raise RuntimeError("This programme can only be run in IDLE")

color.write("     | Game Console | \n", "STRING")

root = Tk()
root.title("Tic-Tac-Toe")
menuFrame = Frame(root)
menuFrame.pack() 
buttonFrame = Frame(root)
buttonFrame.pack()
Label(menuFrame, text = ("Tic-Tac-Toe"), font = ("Helvetica 12 bold")).grid(row = 10, column = 5)

def play():
    color.write("Game window opening... \n", "STRING")
    #open new window to game later



def exe(self):
    color.write("Goodbye for now \n", "STRING")
    self.destroy()

playButton = Button(buttonFrame, text = ("Play game"), command = play)
playButton.pack(side=LEFT)

Button(root, text=("Quit Game"), command=exe).pack()
root.mainloop()

我似乎找不到它的含义,因为我已经在函数中定义了它。提前感谢您的解决方案。在


Tags: textimportselfgame游戏stringtkinterroot
2条回答

在您的代码中,您有:

def exe(self):

这意味着您需要self参数;self与类的实例一起使用,并且由于您的方法没有类,因此可以在方法头中省略self参数,如下所示:

^{pr2}$

方法的定义方式是请求一个(位置)参数self。它通常用作类的对象引用,但由于没有类,所以现在只是一个常规参数,不能传递。可以通过使用匿名函数(lambda)传递该参数,替换:

Button(..., command=exe).pack()

有:

^{pr2}$

您还应该更好地更换:

def exe(self):
    ...
    self.destroy()

有:

def exe(widget_to_be_destroyed):
    ...
    widget_to_be_destroyed.destroy()

为了消除歧义。在

相关问题 更多 >

    热门问题