这是我的代码。我正在尝试使用图形对“连续4个”游戏进行编程,并且我想在按下画布时添加图像:
def player_vs_player(self):
self.pvp = tk.Tk()
main_menu=tk.Button(self.pvp,text="main_menu",bg="black",fg="white",
command=self.main_menu)
main_menu.grid(row=0,column=0)
canvas = tk.Canvas(self.pvp, width=700, height=600, bg="black")
canvas.grid(row=1, column=0, rowspan=6, columnspan=7)
canvas.bind("<Button-1>", self.mouse_callback)
self._root.withdraw()
self.pvp.mainloop()
def mouse_callback(self, event):
self.player = self.game.current_player
ball = tk.Label(self.pvp,image=self.color_match[self.player])
ball.image = self.color_match[self.player]
try:
loc = self.game.make_move(event.x // 100)
ball.grid(row=loc[1], column=loc[0])
except:
tk.messagebox.showinfo("Error", "column is full")
if self.game.get_winner() == 0:
tk.messagebox.showinfo("Game Over!", "It's a tie")
self.close_pvp()
if self.game.get_winner():
tk.messagebox.showinfo("Game Over!", 'Player' + str(self.player)
+ 'has won')
self.close_pvp()
我不断收到此错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Adam\Downloads\WPy-3662\python-3.6.6.amd64\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:/Users/Adam/Documents/ComputerSciense/ex12/gui.py", line 69, in mouse_callback
ball = tk.Label(self.pvp,image=self.color_match[self.player])
File "C:\Users\Adam\Downloads\WPy-3662\python-3.6.6.amd64\lib\tkinter\__init__.py", line 2763, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Adam\Downloads\WPy-3662\python-3.6.6.amd64\lib\tkinter\__init__.py", line 2296, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage3" doesn't exist
init: 这是init,我认为问题不在于字典,因为它配置正确:
def __init__(self):
self._root = tk.Tk()
self.game = Game(Board())
self.player = self.game.current_player
self.blueball = ImageTk.PhotoImage(Image.open("blueball.png").
resize((90, 90), Image.ANTIALIAS))
self.boardimage = ImageTk.PhotoImage(Image.open("b.png").
resize((600, 700),
Image.ANTIALIAS))
self.redball = ImageTk.PhotoImage(Image.open("redball.png").
resize((90, 90), Image.ANTIALIAS))
self.exit = ImageTk.PhotoImage(Image.open('exit.png').
resize((100, 100), Image.ANTIALIAS))
self.pvpimage = ImageTk.PhotoImage(Image.open('pp.png').
resize((100, 100), Image.ANTIALIAS))
self.pvcimage = ImageTk.PhotoImage(Image.open('pcp.png').
resize((100, 100), Image.ANTIALIAS))
self.color_match = {1: self.redball, 2: self.blueball}
self._cv = tk.Canvas(self._root, width=700, height=600, bg="#84d0ff")
答案 0 :(得分:0)
这肯定是由Tk()
的多个实例引起的,正如其他人所说。以下是具有相同错误类型的演示示例:
from tkinter import *
from PIL import ImageTk, Image
# create the image in one Tk instance
win = Tk()
img = ImageTk.PhotoImage(Image.open('redball.png').resize((100, 100)))
# then use the image in another Tk instance
root = Tk()
Label(root, image=img).pack()
root.mainloop()
上述程序将出现以下错误:
_tkinter.TclError: image "pyimage1" doesn't exist
如果您只想在应用程序中有多个窗口,请使用Tk()
作为主窗口,使用Toplevel()
作为其他窗口。