tkinter tic tac toe program

﹥>﹥吖頭↗ 提交于 2019-12-13 02:03:45

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/31718458/tkinter-tic-tac-toe-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!