简体   繁体   English

为什么我的图像出现在 Tkinter 的错误窗口中?

[英]Why is my image appearing on the wrong window in Tkinter?

So I am trying to make a text-based game, but also want to incorporate images into it, I have a main menu, a window that is always open, and then a game window, that should have the image in, but for some reason, it appears in the menu window instead.所以我正在尝试制作基于文本的游戏,但也想将图像合并到其中,我有一个主菜单,一个始终打开的窗口,然后是一个游戏窗口,应该有图像,但对于某些原因,它出现在菜单窗口中。 Has anyone got any idea why?有没有人知道为什么?

def menu():

    master = Tk()
    master.geometry("350x300")
    master.wm_iconbitmap("zombie.ico")
    master.configure(background = '#484a2c')
    master.title("Menu")

    def game():  

        master = Tk()
        master.geometry("800x500")
        master.title("Game")
        master.wm_iconbitmap("zombie.ico")
        master.configure(background = '#484a2c')

        image = PhotoImage(file="Kitchenimage.gif")
        label5 = Label(image=image)
        label5.image = image
        label5.pack()

  label = Label(master, text = "Zombie Mansion", background = '#484a2c',  
  font = ("AR CHRISTY", 30))
  label.pack()

  b = Button(master,text = "Play Game", height = 1, width = 10)
  b.config(background = '#484a2c', activebackground = '#484a2c',  font = 
  ("AR CHRISTY", 14), command = get_username)
  b.place(x = 120, y = 70)


mainloop()

"Why is my image appearing on the wrong window in Tkinter?" “为什么我的图像出现在 Tkinter 的错误窗口中?”

Assuming you have another instance of Tk as what you refer to as main menu somewhere in your code that you're not showing us like:假设您有另一个Tk实例作为您在代码中某处称为主菜单的内容,但您没有向我们展示:

main = Tk()

in addition to master = Tk() in your game method, then it's because when you instantiate widgets without passing a parent widget explicitly like in:除了在您的game方法中使用master = Tk() ,这是因为当您实例化小部件时没有明确传递父小部件,例如:

label5 = Label(image=image)

then the widget's parent defaults to the Tk instance whose mainloop is being run, in above case supposedly main 's.然后小部件的父级默认为正在运行mainloopTk实例,在上面的情况下应该是main的。 By default widgets are shown under their parents, hence the reason.默认情况下,小部件显示在其父项下,因此是原因。

Pass parent explicitly like:明确传递父级,如:

label5 = Label(master=main, image=image)

or或者

label5 = Label(master, image=image)

In most cases, if not all cases, you shouldn't have multiple instances of Tk .在大多数情况下,如果不是所有情况,您不应该有多个Tk实例 If you require additional windows, please use Toplevel widget.如果您需要额外的窗口,请使用Toplevel小部件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM