首页 > 解决方案 > 在子类python中调用父方法

问题描述

这是我的代码:

class GUI(playGame):
    def __init__(self):                          

        import tkinter as tk
        home=tk.Tk()
        home.title("Tic Tac Toe")
        home.geometry("160x180")
        w,h=6,3


        self.c1r1=tk.Button(text='',width=w, height=h, command=lambda: userTurn(self.c1r1))
        self.c1r1.grid(column=1,row=1)
        home.mainloop()

因此,userTurn 已在父类 playGame 中定义,但是当我运行它并单击按钮 c1r1 时,我得到 NameError: name 'userTurn' is not defined

标签: pythonooptkinternameerror

解决方案


您需要self在函数调用中添加一个。你可能应该super()在你的 init 中调用:

import tkinter as tk

class playGame():
    def userTurn(self,foo):
        pass

class GUI(playGame):
    def __init__(self):
        super().__init__()
        home=tk.Tk()
        home.title("Tic Tac Toe")
        home.geometry("160x180")
        w,h=6,3

        self.c1r1=tk.Button(text='',width=w, height=h, command=lambda: self.userTurn(self.c1r1))
        self.c1r1.grid(column=1,row=1)
        home.mainloop()

推荐阅读