我知道这个网站上有解决这个问题的答案,但我遇到的所有决议似乎都没有对我的情况有所帮助。我正在使用Tkinter(并试图学习如何使用它)来制作游戏。我想要一个按钮(退出游戏)退出Tkinter窗口,但我不断收到此错误:
TypeError:exe()缺少1个必需的位置参数:'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()
我似乎无法找到它的含义,因为我已将其定义为函数。提前感谢您的解决方案。
答案 0 :(得分:4)
在您的代码中,您有:
def exe(self):
这意味着您需要self
参数; self
与类的实例一起使用,并且由于您的方法没有类,您可以在方法标题中省略self
参数,如下所示:
def exe():
color.write("Goodbye for now \n", "STRING")
root.destroy()
答案 1 :(得分:0)
您的方法的定义方式是它要求(位置)参数self
。这通常被用作课程的对象参考,但由于你没有课程,所以现在只是一个常规的参数,你没有通过。您可以通过使用匿名函数(lambda)替换:
Button(..., command=exe).pack()
使用:
Button(..., command=lambda widget=root: exe(widget)).pack()
您还应该更好地替换:
def exe(self):
...
self.destroy()
使用:
def exe(widget_to_be_destroyed):
...
widget_to_be_destroyed.destroy()
消除歧义。