Mihai
Mihai

Reputation: 87

Why label not displaying on tkinter window?

I don't know why my label doesn't display on the window. Here is the function that creates the window and label and the link of a image with my problem:

https://i.sstatic.net/gUDbm.jpg

def ask_exit(): 
    ask = Tk()
    ask.geometry("200x100")
    
    img = Image.open("./exit.jpg")
    
    resized = img.resize((200,100))
    
    exit_image = ImageTk.PhotoImage(resized)
    ask_label = Label(ask, image = exit_image, text = "Are you sure\n you want to exit ?")
    ask_label.pack()
    ask_label.grid(column = 0, row = 0)
    
    yes_button = Button(ask, text="Yes",  command = exit)
    yes_button.grid(column = 0, row = 1)
    
    no_button = Button(ask, text="No", command = ask.destroy)
    no_button.grid(column = 1, row = 1)
    
    ask.mainloop()    

The function runs perfectly when is separated from rest of my code. When not using image it also works: the text and the buttons appears.

What do I do wrong ?

Upvotes: 0

Views: 566

Answers (1)

Sriram Srinivasan
Sriram Srinivasan

Reputation: 700

If you want to use an image and a text together in a widget (eg. Label or Button), you need to use the compound parameter to specify where should the image be located with respect to the text. By default, only the image/bitmap is displayed, ignoring the text.

compound can take the following values: center, top, bottom, left or right

In your code, you can use it as follows:

ask_label = Label(ask, image = exit_image, text = "Are you sure\n you want to exit ?", compound = "left")

Corresponding Output:

enter image description here

PS: I used a different image as you did not upload the exit image you have. That's why there is the left arrow in the output.

Upvotes: 2

Related Questions