How to add images inside another window using tkinter? - python

So when I create a window and add an image it works. But then I create a window inside a function and it shows image "pyimage2" doesn't exist. I tried adding the image as a global variable but that doesn't work either (Read on another post that it's a possible fix).
Without global variable:
import tkinter as tk
import os
os.chdir("C:/Users/flare/Desktop/moi/folders/some_files/soundbar program/")
main=tk.Tk()
background=tk.PhotoImage(file="resources/dark_grey_bg.png")
background_label=tk.Label(main,image=background)
background_label.place(x=0,y=0)
def another():
anotherwindow=tk.Tk()
bg=tk.PhotoImage(file="resources/light_grey_bg.png")
bg_label=tk.Label(anotherwindow,image=bg)
bg_label.place(x=0,y=0)
anotherwindow.mainloop()
another()
main.mainloop()
With global variable:
import tkinter as tk
import os
global bg
os.chdir("C:/Users/flare/Desktop/moi/folders/some_files/soundbar program/")
main=tk.Tk()
background=tk.PhotoImage(file="resources/dark_grey_bg.png")
background_label=tk.Label(main,image=background)
background_label.place(x=0,y=0)
def another():
global bg
anotherwindow=tk.Tk()
bg=tk.PhotoImage(file="resources/light_grey_bg.png")
bg_label=tk.Label(anotherwindow,image=bg)
bg_label.place(x=0,y=0)
anotherwindow.mainloop()
another()
main.mainloop()

Posted here: Why photoimages don't exist?
"The second class I defined was the problem cause it used another root window, alias Tk(). An equivalent to the normal Tk() window is the Toplevel() that is the same as a root but hasn't its own interpreter context."
Change the second window to TopLevel().
import tkinter as tk
import os
os.chdir("C:/Users/flare/Desktop/moi/folders/some_files/soundbar program/")
main=tk.Tk()
background=tk.PhotoImage(file="resources/dark_grey_bg.png")
background_label=tk.Label(main,image=background)
background_label.place(x=0,y=0)
def another():
anotherwindow=tk.Toplevel()
bg=tk.PhotoImage(file="resources/light_grey_bg.png")
bg_label=tk.Label(anotherwindow,image=bg)
bg_label.place(x=0,y=0)
anotherwindow.mainloop()
another()
main.mainloop()

Related

Trying to get a variable from a function using tkinter

I've been trying to get the printed output into a variable. Whenever I call the function it just simply repeats the button process. I tried to utilize global, but it doesn't seem to work.
Help pls thanks.
from tkinter import *
from tkinter import filedialog
import tkinter as tk
def openFile():
filepath = filedialog.askopenfilename(title="Open for me")
print(filepath)
window.destroy()
window = tk.Tk()
window.title("Insert Excel File")
window.geometry("200x200")
button = Button(text="Open",command=openFile,height=3,width=10)
button.pack()
window.mainloop()
print , outputs the string to stdout it does not store the value in a variable, you'll need to store it yourself.
Since you're using a callback you can't return the value. The best way to implement this is to use classes, the bad way is to use a global variable to store the result
I'm assuming you are not familiar with classes, so a possible solution would be
from tkinter import *
from tkinter import filedialog
import tkinter as tk
path = ""
def openFile():
global path
path = filedialog.askopenfilename(title="Open for me")
window.destroy()
window = tk.Tk()
window.title("Insert Excel File")
window.geometry("200x200")
button = Button(text="Open",command=openFile,height=3,width=10)
button.pack()
window.mainloop()
# do something with path e.g. print
print(path)

Why do I get an error when I leave out "from tkinter import *"?

In the following code I get an error when leaving out "from tkinter import *. I am confused as to the reason as I import tkinter as tk.
I tried modifying the function set_text without success.
The error is on
self.e.delete(0,END)
NameError: name 'END' is not defined`
Code:
from tkinter import *
import tkinter as tk
from tkinter import ttk
class HelperFun():
def set_text(self,parent,text):
self.e.delete(0,END)
self.e.insert(0,text)
return
def __init__(self,parent):
self.parent=parent
self.e = tk.Entry(self.parent,width=10)
self.e.pack()
self.b1 = tk.Button(self.parent,text="animal",
command=lambda:self.set_text(self.parent,"animal"))
...
root=tk.Tk()
HelperFun(root)
root.mainloop()
Thank you.
When you use, from Tkinter import *, it imports all of the constants from that package, like END.
To get away without using this, you'd need to use the dot operator, like tk.END, otherwise it won't be defined.
If you import tkinter as tk then you need to refer to END as tk.END.
Importing from tkinter import * imports everything in tkinter, making it so you don't have to use the tk qualifying prefix.
replace the line
self.e.delete(0,END)
with
self.e.delete(0,"end")
Your code isn't doing anything. And it is not showing Button
You cannot use self.e simultaneously in the set text() function.
The Button command isn't right.
I modified the code to make it more readability:
import tkinter as tk
class HelperFun():
def __init__(self, parent):
self.parent=parent
self.e = tk.Entry(self.parent,width=10)
self.e.pack()
self.b1 = tk.Button(self.parent,text="animal",
command=lambda:self.set_text(self.e.get()))
self.b1.pack()
self.lb = tk.Label(self.parent, width=10)
self.lb.pack()
def set_text(self, _text):
print(_text)
self.lb.configure(text=_text)
return
root=tk.Tk()
app = HelperFun(root)
root.mainloop()
Screenshot before and after clicking button:
I think in "(0,END)" you need to use 1.0 instead of 0.
Try "(1.0,END)"
END is like Button and Label ...
u have to write tk.END if u (import tkinter as tk)

Why there is a problem while displaying image from different a GUI in different module by making call to the function from another module?

I tried to make a module in which I made a funtion which just reads and display the image in GUI. Then I made another module which makes call to that function when the button is clicked. Button gives me error.
#module code:
from tkinter import *
class disp:
def __init__(self):
root1.geometry("400x500")
image = PhotoImage(file = 'png2.png')
Label(root1,image=image).pack()
root1.mainloop()
#main code:
from tkinter import *
import testimg as ti
def click():
ti.disp()
root = Tk()
Button(text = 'Click me',command=click).pack()
root.mainloop()
In your class disp, you have put the master as root1 whereas in the main code, you have defined Tk() as root. This means that root1 is no window so the label that has a master of root1 has no where to pack itself.
You also need to remove root1.mainloop() because it’s useless and causing errors due to the fact that root1 doesn’t have Tk(). It’s like trying to loop a while statement without typing in while. This gives an error.
Below modified code is based on yours:
#module code:
from tkinter import *
class disp:
def __init__(self):
root1 = Tk()
root1.geometry("400x500")
image = PhotoImage(master=root1, file='png2.png') # set master to root1
Label(root1, image=image).pack()
root1.mainloop()
But using multiple Tk() instances is not a good design.

Tkinter not changing image on button press

I have loaded an image to tkinter label and that image is diplayed in that label.When i press the button i need to change that image.When the button is pressed older image is gone but the new image is not displayed
My code is
import Tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
def change_pic(labelname):
photo1 = ImageTk.PhotoImage(Image.open("demo.jpg"))
labelname.configure(image=photo1)
print "updated"
vlabel=tk.Label(root)
photo = ImageTk.PhotoImage(Image.open('cardframe.jpg'))
vlabel.configure(image=photo)
vlabel.pack()
b2=tk.Button(root,text="Capture",command=lambda:change_pic(vlabel))
b2.pack()
root.mainloop()
In def change_pic(labelname), you need to add labelname.photo = photo1 to make sure photo1 not being garbage collected.
def change_pic(labelname):
photo1 = ImageTk.PhotoImage(Image.open("demo.jpg"))
labelname.configure(image=photo1)
labelname.photo = photo1
print "updated"
P.S. Looks like both labelname.photo = photo1 and labelname.image = photo1 work.
Check this out for more details: http://effbot.org/tkinterbook/label.htm
You can use the label to display PhotoImage and BitmapImage objects.
When doing this, make sure you keep a reference to the image object,
to prevent it from being garbage collected by Python’s memory
allocator. You can use a global variable or an instance attribute, or
easier, just add an attribute to the widget instance.
The following edits were made:
I have organised your code layout and simplified its
syntax where possible. These are to make your code easier to read.
Commonly we make the PIL objects a subset/children of tk.
So long it is a part of root (i.e. it is a child of the root
or any of its child widgets), your PIL objects will work.
Your working code is shown below:
import Tkinter as tk
from PIL import Image, ImageTk
def change_pic():
vlabel.configure(image=root.photo1)
print "updated"
root = tk.Tk()
photo = 'cardframe.jpg'
photo1 = "demo.jpg"
root.photo = ImageTk.PhotoImage(Image.open(photo))
root.photo1 = ImageTk.PhotoImage(Image.open(photo1))
vlabel=tk.Label(root,image=root.photo)
vlabel.pack()
b2=tk.Button(root,text="Capture",command=change_pic)
b2.pack()
root.mainloop()
I got it working with one more line of code:
import tkinter as tk # I am using python 3 on windows so the tkinter is lowercased
from PIL import Image, ImageTk
root = tk.Tk()
def change_pic(labelname):
global photo1 # This is the only new line you need, I believe
photo1 = ImageTk.PhotoImage(Image.open("demo.jpg"))
labelname.configure(image=photo1)
print("updated") # Again I'm using python 3 on windows so syntax may differ.
root.update() # You don't need this statement in this case, but it never hurts
vlabel=tk.Label(root)
photo = ImageTk.PhotoImage(Image.open('cardframe.jpg'))
vlabel.configure(image=photo)
vlabel.pack()
b2=tk.Button(root,text="Capture",command=lambda:change_pic(vlabel))
b2.pack()
root.mainloop()
I believe that the code changes the image locally, so the global statement will change it on the project scope.

Tkinter not working in cmd (working in IDLE)

I am trying to display a directory selection dialog box (for getting a path and then for saving downloaded stuff).The code runs fine in IDLE but when i try to run it in CMD i get this error
NameError: name 'Tk' is not defined
I am using tkinter for gui.
Code Snippet
from tkinter import filedialog
root = Tk()
root.withdraw()
filename = filedialog.askdirectory()
Using Python 3.4.3. Any help/suggestions?
The statement from tkinter import filedialog only imports the filedialog module from tkinter. If you want the usual Tkinter stuff, you have to import that too. I'd recommend import tkinter as tk and then referring to it with e.g. root = tk.Tk() so you don't just dump everything into the global namespace. Or, if you really just want the root object, use from tkinter import Tk.
from tkinter import Tk
from tkinter import filedialog
root = Tk()
root.withdraw()
filename = filedialog.askdirectory()

Categories

Resources