Open window with image using button in Python - python

I want to open a new window which includes an image. I don't know how to achieve this. Currently, my code opens up a plain window with a button saying show image.
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.configure(background = "black")
obrazek = ImageTk.PhotoImage(Image.open("dn.jpg"))
def click():
MyLabel = Label(root, image = obrazek)
Tk()
MyLabel.pack()
myButton = Button(root, text = "Wyjście", command = click, fg = "white", bg = "#000000")
myButton.pack()
mainloop()

This is minimal working example.
You have to use Tk() only to create main window. For other windows you have to use Toplevel. And when you have it in variable ie. top then you have to use it as first argument in Label (or other widget) to display widget in this window.
BTW: PEP 8 -- Style Guide for Python Code
#from tkinter import * # PEP8: `import *` is not preferred
import tkinter as tk
from PIL import ImageTk, Image
# --- functions ---
def click():
top = tk.Toplevel()
my_label = tk.Label(top, image=my_image)
my_label.pack()
# --- main ---
root = tk.Tk()
#root.configure(background="black") # PEP8: without spaces around `=`
my_image = ImageTk.PhotoImage(Image.open("lenna.png")) # PEP8: english names
my_button = tk.Button(root, text="Wyjście", command=click) # PEP8: lower_case_names for variables
my_button.pack()
root.mainloop()
Image from Wikipedia: Lenna
EDIT:
I hope you didn't create PhotoImage inside function because there is bug in PhotoImage which removes image from memory when it is assigned to local variable in function. And then you can see empty image. It has to be assigned to global variable or to some object - ie. my_label.img = image

Related

Unable to Show Label Image inside a Frame using tkinter

'''
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from PIL import ImageTk, Image
root = tk.Tk()
root.geometry("1255x944")
toplevel_frame = ttk.Frame(root)
Title_frame = ttk.Frame(toplevel_frame)
img= tk.PhotoImage(file="logo.PNG")
img = img.subsample(5, 5)
lbl = tk.Label(Title_frame,image=img, compound = tk.LEFT)
lbl.image = img
lbl.grid(row=0,column=0,padx=20, pady=0)
root.mainloop()
'''
It is not showing any error but I am unable to show image inside a frame
As mentioned by #acw1668 in the comments, the frames namely toplevel_frame and Title_frame have not been rendered using any layout function(for more info).
The label with the image(i.e. lbl) is contained within the Title_frame which is within the toplevel_frame. So if the toplevel_frame and the Title_frame are not rendered any widget they contain also would not be rendered. Thus the label with the image(lbl) is not rendered.
This can simply be fixed by using any particular layout function to render these frames.
Using grid the two other lines to be added will look like this -:
toplevel_frame.grid(row=0,column=0)
Title_frame.grid(row=0,column=0)
NOTE: The two lines have to be added in the order they are defined, that is the frames have to be rendered in the order of their definition i.e. toplevel_frame frame first followed by the Title_frame frame followed by the lbl label. This will be more clear looking at the full code as provided below.
With the necessary changes done the full code will look something like this -:
# IMPORTS
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from PIL import ImageTk, Image
# ROOT INITIATION
root = tk.Tk()
root.geometry("1255x944")
# IMAGE OBJECT DEFINITION
img= tk.PhotoImage(file="logo.PNG")
img = img.subsample(5, 5)
# WIDGET DEFINITION
toplevel_frame = ttk.Frame(root)
Title_frame = ttk.Frame(toplevel_frame)
lbl = tk.Label(Title_frame,image=img, compound = tk.LEFT)
lbl.image = img
# LAYOUT MANAGEMENT
toplevel_frame.grid(row=0,column=0) # ADDED.
Title_frame.grid(row=0,column=0) # ADDED.
lbl.grid(row=0,column=0,padx=20, pady=0)
# STARTING THE ROOT MAINLOOP
root.mainloop()
NOTE: Further while deciding on the layout management function to use keep this in mind.

How to put an image inside a function definition?

I want to put an image inside my dice function I would really appreciate if someone can tell me what I need to add so I can have the image as the background of the page
def dice():
tk = Tk()
tk.geometry('300x300')
img = PhotoImage(file='dicee.gif')
lb5 = Label(tk,image=img)
lb5.pack()
btn4=Button(tk,text="Roll The Dice",command=dice)
btn4.place(x=110,y=130)
tk.mainloop()
The error it shows me is:
self.tk.call(
_tkinter.TclError: image "pyimage1" doesn't exist
Actually there are two separate problems with your code. One is that you're creating multiple instances of Tk() which is problematic as #Bryan Oakley mentioned in a comment — create a Toplevel window widget instead.
The other issue is that you're creating the PhotoImage in a function, and since it's a local variable it will be garbage collected when the function returns (see Why does Tkinter image not show up if created in a function?)
Here's code showing how to fix both issues:
from tkinter import *
def dice():
tk = Toplevel() # Create new window.
tk.geometry('300x300')
img = PhotoImage(file='dicee.gif')
lb5 = Label(tk, image=img)
lb5.img = img # Save reference to image.
lb5.pack()
tk = Tk()
btn4 = Button(tk, text="Roll The Dice", command=dice)
btn4.place(x=110, y=130)
tk.mainloop()

Why can't I display an Image in a tkinter Toplevel() window?

I'm trying to create a python program tkinter that, upon the pressing of a button, opens a new full screen tkinter window containing an image and plays an audio file - here's my code:
from tkinter import *
from PIL import Image, ImageTk
from playsound import playsound
def play():
window = Toplevel()
window.attributes('-fullscreen', True)
img = ImageTk.PhotoImage(Image.open("pic.png"))
label = Label(window, image=img).pack()
playsound("song.mp3")
buttonWindow = Tk()
b = Button(buttonWindow, text="Press Button", command=play)
b.pack()
(my image and audio file are both on the desktop with my python file)
However, when I run my code, when I press the button, the audio plays but no second tkinter window opens.
I've tried to destroy() the buttonWindow and have tried many different ways of including an image on a tkinter window - if I remove the line of code using PhotoImage(), the window appears (obviously I then get a syntax error stating that 'img' is not defined).
How could I solve this?
Thanks,
Louis
I had similar problem.
But i resolve this trial and error method.
First of all i don't use pillow library and put image into Label
You should try define Photoimage object NOT IN FUNCTION
Example:
It will work:
import tkinter as tk
root = tk.Tk()
root.geometry("600x400")
def popUp():
popff = tk.Toplevel(root)
popff.geometry("400x200")
labelImgff = tk.Label(popff, image=imgff, bg="white")
labelImgff.grid(row=0, column=0)
imgff = tk.PhotoImage(file="/home/user/image.png")
btnff = tk.Button(text="startPOP", command=popUp)
btnff.grid(column=0,row=0)
root.mainloop()
effect of action
Your playsound() command is blocking execution. The playsound() command has an optional field 'block', which is True by default. Changing this to False will continue execution and allow mainloop() to continue.
Second, just call label.draw() to draw your image to the TopLevel window.
Here's the code:
from tkinter import *
from PIL import Image, ImageTk
from playsound import playsound
def play():
window = Toplevel()
window.attributes('-fullscreen', True)
img = ImageTk.PhotoImage(Image.open("pic.jpeg"))
label = Label(window, image=img).pack()
playsound("song.mp3",block=False)
label.draw()
buttonWindow = Tk()
b = Button(buttonWindow, text="Press Button", command=play)
b.pack()
buttonWindow.mainloop()
Cheers!

Trouble With Tkinter in Python [duplicate]

I'm trying to make a simple outline for a gui, and I'm getting the warning
"variable" May be undefined or defined from star imports: tkinter for all of my variables.
Here is my code:
from tkinter import *
class myApp :
def __init__(self, gui,) :
self.root = gui
self.bframe = Frame(self.root) # Create a container Frame at bottom
self.bframe.pack(side=BOTTOM)
self.xlabel = Label(self.root, text="Item ID") # Create the Label
self.xlabel.pack(side=LEFT)
self.xentry = Entry(self.root, bd=5) # Create the Entry box
self.xentry.pack(side=LEFT)
self.xentry.bind('<Return>', self.showStockItem)
self.xentry.focus_set() # Set focus in the Entry box
self.xopen = Button(self.root, text="Show", command=self.showStockItem) # Create the open Button
self.xopen.pack(side=LEFT)
self.xquit = Button(self.bframe, text="Quit", command=self.quitit) # Create the quit Button
self.xquit.pack(side=BOTTOM)
return
gui = Tk()
gui.title("Travel")
app = myApp(gui)
gui.mainloop()
from tkinter import *
In this line, you import everything from tkinter. This is not recommended, so linter will warn you. But if you really want to do this, it's OK, just ignore it.
To be better, you should explicitly import what you need. For example:
from tkinter import Tk, Label, Frame, Entry, Button
Consider using:
import tkinter as tk
and then, prefix all your calls like:
root = tk.Tk()
or,
variableName.pack(side = tk.LEFT)
and so on...

Unable to place the buttons at required positions using tkinter

I tried the below code but the buttons are placed only at the center only,it is not placed according to my required positioning
from Tkinter import *
import tkFileDialog
from PIL import ImageTk, Image
root = Tk()
def DT(event):
print "Decision tree is selected"
button3 = Button(root, text="Decision Tree",font=("Helvetica", 15))
button3.place(x=50,y=220)
button3.pack()
button3.bind('<Button-1>', DT)
root.minsize(width=1300, height=700)
#root.configure(background='lavender')
root.mainloop()
button3.pack() overrides the placement made by button3.place().
Delete the button3.pack() line.
You are placing and packing the button. Just use either place or pack.

Categories

Resources