-2

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()
Katie
  • 1
  • 1
  • 1
    This code can't possibly create the label in another window because it only creates one window. – Bryan Oakley Feb 25 '18 at 15:36
  • The code above isn't a [mcve]. You claim there are multiple windows but the code presents no evidence for that. Please try to improve the code you've provided. – Nae Feb 25 '18 at 15:39
  • 1
    I apologise, I have now changed it, I just thought it would be a bit long to put all up, it is still not full, but it shows the two windows I am referring about – Katie Feb 25 '18 at 17:51
  • @Katie Please try to fix your indentation. The code above should ideally be runnable with copy/paste-ing, try it yourself to see if it works please. – Nae Feb 25 '18 at 18:39
  • Also seems like what I _guessed_ appear to be correct. – Nae Feb 25 '18 at 18:55

1 Answers1

0

"Why is my image appearing on the wrong window in 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:

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:

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. 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. If you require additional windows, please use Toplevel widget.

Nae
  • 14,209
  • 7
  • 52
  • 79