How to put image in another window in tkinter? - python

I want to put an image in the second window using tkinter, in the first window the code works good, but the second window shows nothing.
In this part I import necessary modules:
from tkinter import filedialog, Tk, Frame, Label, PhotoImage, Button
from PIL import Image
from tkinter import*
import tkinter as tk
Then create the principal window:
raiz = Tk()
raiz.title("ventana")
Then I create the frame and put the image in the frame:
miFrame = Frame()
miFrame.pack()
miFrame.config(width="1400", heigh=("1200"))
fondo=tk.PhotoImage(file="fondoF.png")
fondo=fondo.subsample(1,1)
label=tk.Label(miFrame,image=fondo)
label.place(x=0,y=0,relwidth=1.0,relheight=1.0)
Then a button that will call the second window function:
btn3 = Button(raiz, text="boton")
btn3.place(x=500, y=500)
btn3.config(command=abrirventana2)
Here we have the function which opens the second window and here (I guess) is where I want to put the image.
This part also has two buttons named mih which does nothing in the meantime and ok which calls the function to close the second window:
def abrirventana2():
raiz.deiconify()
ventana2=tk.Toplevel()
ventana2.geometry('500x500')
ventana2.title("ventana2")
ventana2.configure(background="white")
fondov=tk.PhotoImage(file="xxx.gif")
label1=tk.Label(ventana2,image=fondov)
label1.place(x=50,y=50,relwidth=5.0,relheight=5.0)
mensaje=tk.Label(ventana2,text="funciona")
mensaje.pack(padx=5,pady=5,ipadx=5,ipady=5,fill=tk.X)
boton1=tk.Button(ventana2,text='mih')
boton1.pack(side=tk.TOP)
boton2=tk.Button(ventana2,text='ok',command=ventana2.destroy)
boton2.pack(side=tk.TOP)
Function to close the second window:
def cerrarventana2():
ventana.destroy()
I use the mainloop to keep the window open
raiz.mainloop()
Note: I had already tried creating a frame in the second window, but it didn't work.

Apologies for my previously incorrect answer.
The reason the image is not showing is due to the fact that you did not create a reference to it. If you don't create a reference, the image is garbage collected, which doesn't remove it, but in a sense just renders a blank placeholder on the GUI.
In order to display the image correctly you need to add a reference to the image within the code that displays the image.
You therefore now have:
fondov=tk.PhotoImage(file="giphy.gif")
label1=tk.Label(ventana2,image=fondov)
label1.image = fondov
label1.pack()
(label1.image = fondov is the reference)
Sorry for the confusion there. This should work.

Related

Python tkinter placing a button in a grid inside a frame freezes on execution

I have created two frames using Tkinter. In one of the frames I am trying to add a button using a grid. When I run the program, there is no output. Instead it just freezes and I have to kill the process.
Here is the code:
from Tkinter import *
window=Tk()
window.title("calculator")
window.geometry("500x500")
window.resizable(0,0)
input_field=StringVar()
display_frame=Frame(window).pack(side="top")
button_frame=Frame(window).pack(side="bottom")
text=Entry(display_frame,font=('arial',20,'bold'),textvariable=input_field,justify="right").pack(fill="x",ipady=10)
clear_button=Button(button_frame,text="C").grid(row=0)
window.mainloop()
However, if I change the clear_button variable as
clear_button=Button(button_frame,text="C").pack()
I get an output. What am I missing here?
You cannot mix grid and pack inside the same container (a Frame/Window).
That said you should realize that your display_frame and button_frame variables are actually None! Why, because Frame(Window) will return a Frame object, but you have applied the pack() function just after that whose return value is None.
So basically the Entry and the Button widgets that you created have master=None and that means they are not inside the Frames that you defined, but actually part of the main Window.
Now you can easily see why clear_button=Button(button_frame,text="C").pack() was working as now the main window has only one geometry manager namely pack.
Here is the working code.
from tkinter import * # "Tkinter" on python 2
window=Tk()
window.title("calculator")
window.geometry("500x500")
window.resizable(0,0)
input_field=StringVar()
display_frame=Frame(window)
display_frame.pack(side="top")
button_frame=Frame(window)
button_frame.pack(side="bottom")
Entry(display_frame,font=('arial',20,'bold'),textvariable=input_field,justify="right").pack(fill="x",ipady=10)
Button(button_frame, text="C").grid(row=0)
window.mainloop()
You cannot use both grid and pack method on widgets having same master.
Here, follow the below thread for a detailed understanding :
python pack() and grid() methods together

Drag and Drop button tkinter python

I'm new using tkinter on python and I would like to develop a program that can Drag and Drop a button pressing other one... I will try to explain : I have button 'A' that will create a new button 'B' and I want to Drag the New button to another place
Any help
Thanks
The tkinter.dnd module, as suggested by j_4321 in comments.
Here is some sample code using that library to do what you have said:
from tkinter import *
from tkinter.dnd import Tester as DragWindow, Icon as Dragable
# Make a root window and hide it, since we don't need it.
root = Tk()
root.withdraw()
# Make the actual main window, which can have dragable objects on.
main = DragWindow(root)
def make_btn():
"""Make a new test button."""
# The functional part of the main window is the canvas.
Dragable('B').attach(main.canvas)
# Make a button and bind it to our button creating function.
Button(main.top, text='A', command=make_btn).pack()
# Start the mainloop.
mainloop()

Displaying an image in python via Button and Canvas

I am a begginer in python, tkinter. I have written a code that should normally display an image in a canvas.
What happens is that the main frame (gui) is displayed with the menu bar, then when I click on load image, the gui window shrinks (to 100x100 I guess) but nothing is displayed within.
Could you please explain to me why this is happening so I can understand where the error occurs, and how to correct it?
# -*- coding:utf-8 -*-
# Imports
from tkinter import Tk, Menu, Canvas
from PIL import Image, ImageTk
# Function definitions
def deleteImage(canvas):
canvas.delete("all")
return
def loadImage(canvas, img):
filename = ImageTk.PhotoImage(img)
canvas.image = filename
canvas.create_image(0,0,anchor='nw',image=filename)
return
def quitProgram():
gui.destroy()
# Main window
gui = Tk()
# Inside the main gui window
#Creating an object containing an image
# A canvas with borders that adapt to the image within it
img = Image.open("fleur.jpg")
canvas = Canvas(gui,height=img.size[0],width=img.size[0])
canvas.pack()
# Menu bar
menubar = Menu(gui)
# Adding a cascade to the menu bar:
filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Files", menu=filemenu)
# Adding a load image button to the cascade menu "File"
filemenu.add_command(label="Load an image", command=loadImage)
# Adding a delete image button to the cascade menu "File"
filemenu.add_command(label="Delete image", command=deleteImage)
filemenu.add_separator()
filemenu.add_command(label="Quit", command=quitProgram)
menubar.add_separator()
menubar.add_cascade(label="?")
# Display the menu bar
gui.config(menu=menubar)
gui.mainloop()
EDIT:
The second problem is that I want to create a canvas and the image in the main gui window, and pass them as arguments to the menu buttons (See code above, where img and canvas are created separately from the function loadImage). Seeing as putting parenthesis in the command=loadImage() created a problem on its own.
Another point that rises a question in my head : Regarding the first problem which was solved by keeping a reference to the filename=ImageTk.PhotoImage(img). Wouldn't it normally be pointless to keep a reference inside the function since it's a local variable anyway?
As stated in effbot's PhotoImage page, you have to keep a reference of your image to ensure it's not garbage collected.
You must keep a reference to the image object in your Python program,
either by storing it in a global variable, or by attaching it to
another object.
Note: When a PhotoImage object is garbage-collected by Python (e.g.
when you return from a function which stored an image in a local
variable), the image is cleared even if it’s being displayed by a
Tkinter widget.
To avoid this, the program must keep an extra reference to the image
object. A simple way to do this is to assign the image to a widget
attribute, like this:
Your loadImage() method should look like below.
def loadImage():
img = Image.open("fleur.jpg")
filename = ImageTk.PhotoImage(img)
canvas = Canvas(gui,height=100,width=100)
canvas.image = filename # <--- keep reference of your image
canvas.create_image(0,0,anchor='nw',image=filename)
canvas.pack()

Python Tkinter: How do I apply a new background image when opening a new tk window?

I used the code below (with different variable names for each section) to create a background image for each tkinter window. Each of these is initiated in a function and both work fine independently.
When loading one function from another however, the second fails to display an image. (I have tried importing all relevant in each function aswell). It works in the case that use tk.destruct(), however if If I want to keep it open, or hide it with . withdraw(), the image fails to display, rendering the second window useless.
background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
Ok I've made up a solution for you. Basically all you need is to use tk.Toplevel() for the second tkinter window and make sure that the 'parent' is root2 so the image will appear in the second window.
I have used buttons for the images, you had labels so you may wish to change this, but buttons gave me a way to open a new tk window easily, I have also used .pack(), not .place(), as it was faster for me. May also be helpful for you to know that I used python 3.3 with windows so you might need a capital T for tkinter.
import tkinter as tk
root1 = tk.Tk()
def new_window():
root2 = tk.Toplevel()
# click the last button and all tk windows close
def shutdown():
root1.destroy()
root2.destroy()
background_image2 = tk.PhotoImage(file = '...')
background_button2 = tk.Button(root2, image = background_image2, command = shutdown)
background_button2.pack()
root2.mainloop()
background_image1 = tk.PhotoImage(file = '...')
# have used a button not a label for me to make another tk window
background_button1 = tk.Button(root1, image = background_image1, command = new_window)
background_button1.pack()
root1.mainloop()
#user2589273 Next time you should add more code so answers can be easily given, and tailored to you, just a suggestion. Hope this helps.

Python/Tkinter Image and Text label collision

I've been tinkering around with Python lately and wanted to make a GUI that reads from a CSV and displays it correctly.
CSV build up:
name,description,image location
steven,some guy,/res/pic/steven.gif
the first two entries should be put in text labels, and the last entry should be used as an image.
In my code I got as far as inserting the picture, which worked. But as soon as I also embedded the text label, I think the application runs into an infinity loop.
If I delete the Image from the code, the text label works and vice versa.
from Tkinter import *
from PIL import *
import os
import csv
#Functions
def insertImage(guiName,picture,x,y):
#This is the Image label insertion, delete it and Text label works
img = PhotoImage(file=entryList[picture][2])
preview = Label(guiName, image=img)
preview.img = img
preview.grid(row=x,column=y)
#This is the Text label insertion, delete it and Image Label works
Name = StringVar()
labelName = Label(mainGUI, textvariable=Name, justify=LEFT)
Name.set(entryList[picture][2])
labelName.pack()
global mainGUI
mainGUI = Tk()
mainGUI.geometry("500x500")
mainGUI.title('Index')
reader = csv.reader(open("res/test.csv", "rb"))
entryList = []
for row in reader:
entryList.append( row )
#insertImage(mainGUI,entryList[1][2],1,1)
insertImage(mainGUI,1,1,1)
#insertImage(mainGUI,2,2,1)
mainGUI.mainloop()
Does anyone have an idea what the problem might be?
The problem is that you are using grid() and pack() to position widgets within the same master widget (mainGUI). That won't work, because by default both of those geometry managers attempt to manage the size of the parent widget and end up fighting over the size (which blocks the GUI from ever appearing as a side effect).
The very latest version of Tk (the lib underneath Tkinter) will throw an error if you try to do this (finally!) but your best bet is to just use one geometry manager per parent widget. (There are some subtleties with disabling geometry propagation which can make this work, and “parent” can be a touch tricky in a few situations, but the key issue is that you're doing the wrong thing in the first place.)
Also, a single label can contain both an image and some text; see the compound option (which enables this and controls the relative placement rules).

Categories