Adding an image to a button in Tkinter

后端 未结 2 1004
太阳男子
太阳男子 2021-01-13 18:02

I am trying to add an image to a button, but I have got some issues when I try to execute the current code. All it shows is an image with no words. I can\'t even see the but

2条回答
  •  抹茶落季
    2021-01-13 18:46

    You need to pack (or grid) your button in the window, here is how you could do:

    import tkinter as tk
    from tkinter import PhotoImage
    
    def print_hello():
        print('hello')
    
    root = tk.Tk()
    root.geometry("960x600")
    
    imagetest = PhotoImage(file="giftest.gif")
    
    button_qwer = tk.Button(root, text="asdfasdf", image=imagetest, command=print_hello)
    button_qwer.pack()   # <-- don't forget to place the button in the window
    
    root.mainloop()
    

    You can have both text and image displayed on your button, using the compound option, like this:

    button_qwer = tk.Button(root, image=imagetest, text="asdfasdf", compound="top", command=print_hello) 
    

    compound options are bottom, center, left, none, right, or top

提交回复
热议问题