Python tkinter tic tac toe程序
我正在试验tkinter,并考虑实现一个简单的井字游戏。这是我想到的Python tkinter tic tac toe程序,python,python-3.x,tkinter,tic-tac-toe,Python,Python 3.x,Tkinter,Tic Tac Toe,我正在试验tkinter,并考虑实现一个简单的井字游戏。这是我想到的 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.
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()
执行此操作时,不会显示任何内容。我的当前文件夹中有该图像。为了验证我是否做对了,我将我的主要部分更改为:
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()
通过在Gui类中注释相应的代码,它可以正常工作。有人能告诉我为什么会这样吗?我花了好几个小时试图弄明白这一点。保持对
PhotoImage
的引用,不要垃圾收集。只需将对象保存为实例变量即可解决此问题:
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()
def\uuuuu init\uuuuuuuuuu(自,主):
超级()。\uuuu初始化\uuuuu(主)
self.parent=master
自我、父母、头衔(“tic-tac-toe”)
self.logo=tk.PhotoImage(file=“X.png”)#保持对PhotoImage
的引用不被垃圾收集。只需将对象保存为实例变量即可解决此问题:
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()
def\uuuuu init\uuuuuuuuuu(自,主):
超级()。\uuuu初始化\uuuuu(主)
self.parent=master
自我、父母、头衔(“tic-tac-toe”)
self.logo=tk.PhotoImage(file=“X.png”)#感谢您的回答。我终于能在你的帮助下解决这个问题了谢谢你的回答。终于在你的帮助下解决了