This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 9 months ago.
I am trying to display an image in a window with tkinter, by clicking a button.
I created this function :
def tabuim():
tabu = Frame(win, width=600, height=400)
tabu.pack()
tabu.place(anchor='center', relx=0.8, rely=0.35)
img2 = ImageTk.PhotoImage(Image.open("Tabu.jpg"), master=win)
label2 = Label(tabu, image = img2, borderwidth=3, relief="solid")
label2.pack()
with this button :
button2 = Button(win, text = 'Tabu Route Solution', command = tabuim)
button2.place(relx = 0.5, rely = 0.5)
But it partially works. It only show a border without my image...
Thanks for you help
The following example displays a background image in a frame:
Import tkinter
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
Create a photoimage object of the image in the path
image1 = Image.open("<path/image_name>")
test = ImageTk.PhotoImage(image1)
label1 = tkinter.Label(image=test)
label1.image = test
Position image
label1.place(x=<x_coordinate>, y=<y_coordinate>)
root.mainloop()
This an example you can do as instead of resizing before loading the page you could resize after the image is loaded.
Related
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 6 months ago.
I am trying to make a sprite sheet editor.
I have a button where you can select an image.
When I put the code in a function it doesn't work, but when it is outside a function it does work.
The BrowseComputer function is what I am having a problem with
from tkinter import *
from tkinter import filedialog
#Window specs
window = Tk()
window.title("TileSplit")
window.configure(background="white")
filepath = ""
#Searches computer and displays Image
def BrowseCompter():
filepath = filedialog.askopenfilename()
photo = PhotoImage(file = filepath)
print(filepath)
SelectedImage = Label(window, image=photo, bg="White").grid(row=0,column=0)
#Makes a variable with information about the instruction text on the screen, Sets the text background, Text color, font and location
InstructionsLabel = Label(window, text="Please select the image you would like to split:" ,bg="white" ,font= "none 12 bold")
EmptyLabel = Label(window, text="" ,bg="white" ,font= "none 12 bold")
#Makes a button
ImportImageButton = Button(window, text="Browse:", command=BrowseCompter)
#Location data
InstructionsLabel.grid(row=0, column=60, sticky=E)
ImportImageButton.grid(row=3,column=0)
EmptyLabel.grid(row=1, column=0)
#Tells python to make the window
window.mainloop()
I think you have a typo. The function shown is actually named 'BrowseCompter'.
also you might need to change your command in the button from 'BrowseCompter' to 'BrowseCompter()'
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 10 months ago.
I was trying to show the image when I clicked the button however it failed( the program does not report an error but the image is still not displayed). I'm sure I put the right path to the picture. This is code
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
def def_btn1():
image1 = Image.open("csdl.png")
image1 = image1.resize((710, 400), Image.ANTIALIAS)
test = ImageTk.PhotoImage(image1)
lbl2 = tk.Label(image=test)
lbl2.pack()
btn1 = tk.Button(text="click to show", relief=tk.RIDGE, width=15, font=(12),command=def_btn1)
btn1.pack()
window = tk.mainloop()
I want when I click the button the image will show in the program. Thank you!
You need to add lbl2.image = test for the image to not be destroyed by tkinter, you new code should be this -
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk() # You might want to move this line below your functions, with the other global variables
def def_btn1():
image1 = Image.open("csdl.png")
image1 = image1.resize((710, 400), Image.ANTIALIAS)
test = ImageTk.PhotoImage(image1)
lbl2 = tk.Label(image=test)
lbl2.image = test # You need to have this line for it to work, otherwise it is getting rid of the image. the varibale after the '=' must be the same as the one calling "ImageTk.PhotoImage"
lbl2.pack()
btn1 = tk.Button(text="click to show", relief=tk.RIDGE, width=15, font=(12),command= lambda : def_btn1()) # adding 'lambda :' stops the function from running straight away, it will only run if the button is pressed
btn1.pack()
window = tk.mainloop()
The following project is supposed to show a message when clicking a certain colored button. But, whenever I execute the program it shows blank(white) buttons in the correct alignment, etc. Due to some reason the images are not loaded.
In future, I plan to add different images hence testing with colored image created in Paint and not in-built commands to show the color.
I will add the result below after the code.
Edit: All images are 100x100 pixels created in Microsoft Paint.I have tried other modules like PIL but to no avail.
# importing the module
import tkinter
import tkinter.messagebox
from tkinter import *
# importing the module
# initialising tkinter
class window(Frame):
def __init__(self,master = None):
Frame.__init__(self,master)
self.master = master
# initialising tkinter
# creating the window
root = Tk()
app = window(root)
root.geometry("350x350")
# creating the window
# colours
WHITE = (255,255,255)
BLACK = (0,0,0)
BLUE = (0,0,255)
RED = (255,0,0)
# colours
# image
red_image = "red.png"
blue_image = "blue.png"
yellow_image = "yellow.png"
green_image = "green.png"
# image
# creating a button function
def create_button(x,y,color,color2,picture):
click = Button(root, image = PhotoImage(picture), width= 150, height=150, command = lambda : tkinter.messagebox.showinfo( "Hello Python", "This is " + color))
click.image = PhotoImage(picture)
click.grid( row = x, column = y)
# creating a button function
create_button(0,0,'red','pink',red_image)
create_button(0,2,'blue','lightblue',blue_image)
create_button(2,0,'green','lightgreen',green_image)
create_button(2,2,'yellow','lightyellow',yellow_image)
# starting the widget
root.mainloop()
# starting the widget
There are two issues in your code:
You passed filename to PhotoImage() without using file keyword: PhotoImage(picture) should be PhotoImage(file=picture)
You did not keep the reference of the image assigned to button, but another instance of image
Below is the updated create_button() function that fixes the issues:
def create_button(x, y, color, color2, picture):
image = PhotoImage(file=picture)
click = Button(root, image=image, width=150, height=150, command=lambda: tkinter.messagebox.showinfo("Hello Python", "This is "+color))
click.image = image
click.grid(row=x, column=y)
For adding image in Button you have not use appropriate keywords.
Here is a simple example for you to add image in button
from tkinter import *
from tkinter.ttk import *
# creating tkinter window
root = Tk()
# Adding widgets to the root window
Label(root, text = 'Image adding', font =( 'Verdana',15)).pack(side = TOP, pady = 10)
# Creating a photoimage object to use image
photo = PhotoImage(file = "C:\Gfg\circle.png")
# here, image option is used to
# set image on button
Button(root, text = 'Click Me !', image = photo).pack(side = TOP)
root.mainloop()
I think it may help you
This question already has an answer here:
Python Tkinter Error, "Too Early to Create Image"
(1 answer)
Closed 4 years ago.
I am trying to create an image library and to call an image from that image library in tkinter. But this code gives me an error:
This is the image library file img.py:
from tkinter import *
food_0001 = PhotoImage(file='food_0001.gif')
food_0002 = PhotoImage(file='bg.gif')
This is the file intended to open images stored in img.py:
from tkinter import *
import img
window = Tk()
window.title('image')
canvas = Canvas(window, width = 800, height = 800)
canvas.pack()
canvas.create_image(0,0, anchor=NW, image=food_0001)
window.mainloop()
It is because PhotoImage() can only be called after creation of Tk().
Suggest to rewrite img.py to create PhotoImage() only when it is needed. Below is a sample way to do it:
from tkinter import *
imagelist = {
'food_0001': ['food_0001.png', None],
'food_0002': ['bg.png', None],
}
def get(name):
if name in imagelist:
if imagelist[name][1] is None:
print('loading image:', name)
imagelist[name][1] = PhotoImage(file=imagelist[name][0])
return imagelist[name][1]
return None
Then modify your main program to cater the change:
from tkinter import *
import img
window = Tk()
window.title('image')
canvas = Canvas(window, width=800, height=800)
canvas.pack()
canvas.create_image(0, 0, anchor='nw', image=img.get('food_0001'))
window.mainloop()
Of cause there are many other ways to do it and it depends on your imagination.
I am trying to make tk buttons look better by adding a button background. The issue is, I can use an image or text, but not both, for a tk button.
How can you have both?
This is what I have tried:
from tkinter import *
from PIL import Image, ImageTk
print("I ran")
master = Tk()
canvas_width = 800
canvas_height = 400
window = Canvas(master,
width=canvas_width,
height=canvas_height)
img = Image.open("images/button_black.png").resize((80,40))
ph_image = ImageTk.PhotoImage(img)
l = Label(master, text='Button', image=ph_image, compound=CENTER, fg="white")
l.pack(side=LEFT)
button = Button ( master, image=l)
window.pack()
mainloop()
To use both an image and text you must set the compound option. From the canonical documentation:
Specifies if the widget should display text and bitmaps/images at the same time, and if so, where the bitmap/image should be placed relative to the text. Must be one of the values none, bottom, top, left, right, or center. For example, the (default) value none specifies that the bitmap or image should (if defined) be displayed instead of the text, the value left specifies that the bitmap or image should be displayed to the left of the text, and the value center specifies that the bitmap or image should be displayed on top of the text.
Example:
The following example uses this image:
The program renders like this when using compound="center":
import tkinter as tk
image_data = '''
R0lGODdhyABkAKIAAAAAAP8mAP/7AP///wAAAAAAAAAAAAAAACH5BAkAAAQALAA
AAADIAGQAAAP/KLrc/jDKSau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru987/
/AoHBILBqPyKRyyWw6n9CodEqtWq/YrHbL7Xq/4LB4TC6bz+i0es1uu9/wuHxOl
wTu+Lx+z+8H6jZ+goOEg4AnhYmKi3yHHIyQkZGOE5KWl5CUCpicnYx1nqGihHCj
pqd+a6irrHlnrbCwY7G0sl+1uKxeubyoXL3AplnBxMJWxciex8nMmFXN0JJU0dS
ZUtXYiVPZ3ILb3eB63+Hk4+Tg5ufc6erY0+3Zz/Du8vPQV/bRw/nFv/zAu/7lAi
Ow1qyCq14hFKVqobM3Dj/RiUhKE0U8miIUzIihNh3HEPo+toglsqTJkyhTqlzJs
qXLlzBjypxJs6bNmzhz6tzJs6fPn0CDCh1KtKjRo0iTKlWZAAA7
'''
root = tk.Tk()
image = tk.PhotoImage(data=image_data)
label = tk.Button(root, image=image, text="Hello, world", compound="center")
label.pack(padx=20, pady=20)
root.mainloop()