4

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 button either. Is there some way of fixing my current code?

from tkinter import *
import tkinter as tk

root = tk.Tk()
root.geometry("960x600")

canvas = Canvas(root, width=500, height=500)
canvas.pack()

imagetest = PhotoImage(file="giftest.gif")
canvas.create_image(250, 250, image=imagetest)

button_qwer = Button(root, text="asdfasdf", image=imagetest)

root.mainloop()

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

By the way, is it actually possible in Python to get buttons that have both the image and the text? I was initially intending for a method of getting both the image and the text showing, but at least I got my button to show an image. Currently, I've got only the image showing up.
Yes, it is possible, like this: button_qwer = tk.Button(root, image=imagetest, text="asdfasdf", command=print_hello, compound="top")
0

You are making the button successfully but you are not drawing it onto the screen/interface. Use pack , place or grid.

button_qwer = Button(root, text="asdfasdf", image=imagetest)
button_qwer.pack()

Your full code can be like:

from tkinter import *
import tkinter as tk

root = tk.Tk()
root.geometry("960x600")

canvas = Canvas(root, width=500, height=500)
canvas.pack()

imagetest = PhotoImage(file="giftest.gif")
canvas.create_image(250, 250, image=imagetest)

button_qwer = Button(root, text="asdfasdf", image=imagetest)
button_qwer.pack()
root.mainloop()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.