Search code examples
pythonpython-3.xtkintertic-tac-toe

tkinter tic tac toe program


I was experimenting with tkinter and thought of implementing a simple tic-tac-toe game. here is what i came up with

import tkinter as tk

class Gui(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.parent = master
        self.parent.title("tic tac toe")
        logo = tk.PhotoImage(file="X.png")
        for i in range(3):
            for j in range(3):
                w = tk.Label(self,image=logo)
                w.grid(row=i, column=j)

        self.pack()

if __name__ == '__main__':
    root = tk.Tk()
    logo = tk.PhotoImage(file="X.png")
    f = Gui(root)
    root.mainloop()

when i execute this nothing is being displayed. I have the image in my current folder. Just to verify if i was doing it right i changed my main part to:

if __name__ == '__main__':
    root = tk.Tk()
    logo = tk.PhotoImage(file="X.png")
    f = Gui(root)
    for i in range(3):
        for j in range(3):
            w = tk.Label(f,image=logo)
            w.grid(row=i, column=j)
    f.pack()
    root.mainloop()

by commenting the respective code in Gui class and it works. can someone tell me why is this so? I ve spent hours trying to figure this out.


Solution

  • Keep reference to the PhotoImage not garbage collected. Simply saving the object as instance variable will solve the issue:

    def __init__(self, master):
        super().__init__(master)
        self.parent = master
        self.parent.title("tic tac toe")
        self.logo = tk.PhotoImage(file="X.png")  # <----
        for i in range(3):
            for j in range(3):
                w = tk.Label(self, image=self.logo)  # <---
                w.grid(row=i, column=j)
    
        self.pack()