tkinter:按下按钮以添加新图像错误 - python

这是我的代码。我正在尝试使用图形对游戏“连续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,我认为问题不在于字典,因为它配置正确:

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

参考方案

正如其他人所说,这肯定是由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()作为其他窗口。

Tk / Tkinter:检测应用程序失去焦点 - python

我正在申请Tkinter。在应用程序中,我想弹出一个上下文菜单,这是使用Tk.Menu.post()完成的。当应用程序失去焦点时,我不知道如何使此菜单消失。我需要执行此操作,因为即使在切换到另一个窗口时,菜单仍停留在最上面,而使菜单保留为“工件”。我在菜单上放置了一个<FocusOut>事件,如果菜单具有焦点并且用户将焦点移至另一个应用程序,则会…

Tkinter:在背景图片上方覆盖标签 - python

我正在尝试使用Python和Tkinter创建我的第一个GUI。我想要一个背景图像,该图像随窗口大小以及在背景顶部的两个标签相应地调整大小,两个标签都放置在窗口的中间位置。两个标签是“全名”和“教育”,如下面的代码所示。当前,我正在使用pack()方法,并且一直在使用here中的窗口大小调整代码。我的问题是:如何使标签与背景图像重叠(代码中也包含标签)?用我…

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…

Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…