Troubles uploading images in tkinter [duplicate] - python

I am a newbie to python.I have a code where the image is not printed on the Tkinter.So please help me on how to display the image along with the Button and Textbox.
Code:
import Tkinter
from Tkinter import *
class myproject(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self)
self.button2()
self.text()
self.image()
def button2(self):
button2 = Tkinter.Button(self, text = "hello")
button2.grid(column=5,row=7)
def text(self):
text = Tkinter.Text(self, height=3, width=31) # self.text
text.grid(column=1,row=3)
text.insert(END, "Wiilliam Skakespeare")
def image(self):
logo = PhotoImage(file="linux.gif")
w1 = Tkinter.Label(self, image=logo).pack(side="right")
app = myproject(None)
app.mainloop()
Please help!Answers will be appreciated!

You have to save a reference to the photo image.
See this page for more information, or this one
There are numerous other problems with the code you posted, however; you need colons after function and class declarations, for example. When posting code, there's also no need for extraneous methods in the class, they only make it more difficult to understand
You also cannot mix managers or you're whole program might stall. This means you shouldn't be using pack and grid in the same program. Read through the effbot tutorial, it's really helpful!
class myproject(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self)
self.image()
def image(self):
logo = Tkinter.PhotoImage(file='linux.gif')
self.logo = logo # You always need a reference to the image or it gets garbage collected
w1 = Tkinter.Label(self, image=logo).grid()
app = myproject(None)
app.mainloop()

Related

Image is not showing up on tkinter canvas

Updated after being able to replicate te problem.
Initially I could make it work by binding a key to the canvas, why that worked I do not know, but then that stopped working too so I investigated further.
After setting up some tests I managed to make a short code that replicates the problem:
from tkinter import *
class SomeClass:
def __init__(self, master):
self.can = Canvas(master, bg="gray")
self.can.pack()
thing = PhotoImage(file=("./img/thing.PNG"))
img = self.can.create_image(20, 20, image=thing)
stuff = self.can.find_all()
print(stuff)
app = Tk()
SomeClass(app) # Does not work
something = SomeClass(app) # Dos not work
# This part does work:
can = Canvas(app, bg="gray")
can.pack()
thing = PhotoImage(file=("./img/thing.PNG"))
img = can.create_image(20, 20, image=thing)
stuff = can.find_all()
print(stuff)
app.mainloop()
In all cases, the img show up as an item in the find_all(), but the first two does not show it on the canvas.
Also tried to put the creation of the image as a method with a bind to activate it thinking it went wrong during the init part. This did not change anything.
So what am I doing wrong here?
So answering my own question as I finally found out what was going wrong.
I didn't read this line in the documentation about the PhotoImage:
"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."
So in this case, the way to make it work is either do:
app = Tk()
thing = PhotoImage(file=("./img/thing.PNG")) # making it a global variable
or
class SomeClass:
def __init__(self, master):
self.can = Canvas(master, bg="gray")
thing = PhotoImage(file=("./img/thing.PNG")
self.can.img = thing # This attaches the image to the canvas object
Hope this helps anyone else that comes across this problem.

adding image to tkinter gui

I am new to Tkinter. I want to create a GUI that can support embedding audio files and that also has a background image. I have tried endlessly to install pygame to no avail. I cannot seem to figure out why it is not installing correctly so at this point I am just trying to find the easiest way possible to have these two options. Below is my attempt at displaying a background image using a canvas widget. However, I always get an error that my variables are not defined. I would really appreciate some feedback on what I am doing wrong, as well as any helpful tkinter tutorials that involve more than just the basics. Thanks in advance
from Tkinter import *
root = Tk()
root.geometry("500x500")
class Application(Frame):
def __init__(self, master):
#initialize the frame
Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
self.can = Canvas(root, width=160, height=160, bg='white')
self.pic = PhotoImage(file='speaker.gif')
self.item = can.create_image(80, 80, image=pic)
app = Application(root)
#kick off event loop
root.mainloop()
Every time you want to use an attribute of a class inside one of its methods, you need to prefix it with self.:
self.item = self.can.create_image(80, 80, image=self.pic)
# ^^^^^ ^^^^^
Otherwise, Python will treat the names as being local to the function and will raise an exception when it fails to find them.
Also, you forgot to call grid on your canvas widget:
self.can = Canvas(root, width=160, height=160, bg='white')
self.can.grid(...)
As for resources on Tkinter, you can check out these:
http://www.tkdocs.com/tutorial/onepage.html
http://effbot.org/tkinterbook/

Tkinter Class method

Okay, i've been trying to create a small text editor in Tkinter. I've stubble across a problem and I can't seem to find the answer. If anyone could just help me, I'd be very happy.
First of all, here is my code :
import tkinter as tk
import tkinter.filedialog as tkfile
class PyTedi(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
# Instantiate Menu
main_menu = tk.Menu(self)
menu_bar = PyTediMenu(main_menu)
main_menu.add_cascade(label='File', menu=menu_bar)
self.config(menu=main_menu)
# Instantiate Text Area
text_area = PyTediTextArea(self)
text_area.pack(side=tk.BOTTOM)
# Instantiate Tool Bar
tool_bar = PyTediToolBar(self)
tool_bar.pack(side=tk.TOP)
class PyTediMenu(tk.Menu):
def __init__(self, parent):
tk.Menu.__init__(self, parent)
self.add_command(label='New', command=None)
self.add_command(label='Open', command=None)
self.add_command(label='Save', command=tkfile.asksaveasfile)
self.add_separator()
self.add_command(label='Exit', command=self.quit)
class PyTediToolBar(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, height=30)
class PyTediTextArea(tk.Text):
def __init__(self, parent):
tk.Text.__init__(self, parent)
if __name__ == '__main__':
app = PyTedi()
app.mainloop()
Basically, I've found out, (From another stack question) That it is a good idea to create class based components... My problem is, let's say I want to create a command -> Save File. So I create a method inside my Menu and link to the save function. BUT, how do I grab the text area content and write it to a file ? They are not even part of the same class. Is it a bad design implementation or it's just me ?
Thanks !
while it is a good idea to use class based programming, i would like to point out that unless you are modifying the widget in some way, subclassing it is completely unnecessary, when you create the class PyTediTextArea you aren't actually modifying the original text class in any way, so it would be simpler for you to simply change
text_area = PyTediTextArea(self)
to
self.text_area = tk.Text(self)
that way you save yourself subclassing at the bottom and from anywhere in your main class you can simply call
self.text_area.get(0, "end")
to get all of the text in the widget
James

Python: Tkinter not displaying my image or UI

I am trying to create a user interface with a picture in its top right corner. Here is my code:
import tkinter as tk
import urllib.request
import base64 as b64
class my_ui(tk.Tk):
def __init__(self, parent):
tk.Tk.__init__(self,parent)
self.parent=parent
self.intialize()
def intialize(self):
self.grid()
#Welcome
label = tk.Label(self,text="Welcome to my UI", anchor='center',fg='white',bg='blue')
label.grid(column=0,row=0,columnspan=2,rowspan=2,sticky='EW')
#Buttons
button = tk.Button(self,text="Button 1",command=self.OnButtonClick)
button.grid(column=0,row=3,sticky='W')
def OnButtonClick(self):
print("You clicked the button!")
if __name__ == "__main__":
app = my_ui(None)
#Logo URL - just a smiley face
URL = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQCItlNQe0QaiuhkADUwgVTpx-Isaym6RAP06PHkzBe2Yza3a4rYIkHuB8"
u = urllib.request.urlopen(URL)
raw_data = u.read()
u.close()
b64_data = b64.encodestring(raw_data)
photo = tk.PhotoImage(data=b64_data)
logo = tk.Label(app, image=photo)
logo.image = photo # To save it in memory
logo.pack() # If I exclude this line, UI works fine.
app.title('My User Interface')
app.mainloop()
I am pulling a .gif from the web and returning a PhotoImage with my function. When I run this, I get no errors - rather, my tkinter window does not appear whatsoever. When I take out the line I mentioned in the comment, my UI comes up fine (buttons, but no image) with no errors.
I am unsure of what exactly the absence of the window means. I am running Python 3.4.1 on Mac OSx. Any help would be greatly appreciated!
When a tk.PhotoImage object gets garbage collected, the image is "released", so to speak. The image is still technically being used, so it's not destroyed, but it will get completely blanked out. Replace your return line with:
photo = tk.PhotoImage(data=b64_data)
return photo
Just be sure to declare photo as a global variable.

Window with tk to get text

I'm building a small educational app.
I already have all the code done, all I'm missing is a way is getting a window to open with TK displaying a textbox, an image and a button.
All it should do, it return the text inserted in the textbox after clicking the button and closing the windows.
So, how do I do this?
I have been looking at code, but nothing I did worked, I almost fell ashamed being this so basic.
Thanks
An easy way to write GUIs is using Tkinter. There's an example that display a windows with a text and a button:
from Tkinter import*
class GUI:
def __init__(self,v):
self.entry = Entry(v)
self.entry.pack()
self.button=Button(v, text="Press the button",command=self.pressButton)
self.button.pack()
self.t = StringVar()
self.t.set("You wrote: ")
self.label=Label(v, textvariable=self.t)
self.label.pack()
self.n = 0
def pressButton(self):
text = self.entry.get()
self.t.set("You wrote: "+text)
w=Tk()
gui=GUI(w)
w.mainloop()
You may look at the Tkinter documentation, the label widget also supports to include pictures.
Regards
This is a simple code that get the input from the inputBox to myText. It should get you started on the right direction. Depending on what else you need to check or do, you can add more functions to it. Notice you might have to play around with the order of the line image = tk.PhotoImage(data=b64_data). Because if you put it right after b64_data = .... It will gives you error. (I am running MAC 10.6 with Python 3.2). And the picture only works with GIF at the moment. See reference at the bottom if you want to learn more.
import tkinter as tk
import urllib.request
import base64
# Download the image using urllib
URL = "http://www.contentmanagement365.com/Content/Exhibition6/Files/369a0147-0853-4bb0-85ff-c1beda37c3db/apple_logo_50x50.gif"
u = urllib.request.urlopen(URL)
raw_data = u.read()
u.close()
b64_data = base64.encodestring(raw_data)
# The string you want to returned is somewhere outside
myText = 'empty'
def getText():
global myText
# You can perform check on some condition if you want to
# If it is okay, then store the value, and exist
myText = inputBox.get()
print('User Entered:', myText)
root.destroy()
root = tk.Tk()
# Just a simple title
simpleTitle = tk.Label(root)
simpleTitle['text'] = 'Please enter your input here'
simpleTitle.pack()
# The image (but in the label widget)
image = tk.PhotoImage(data=b64_data)
imageLabel = tk.Label(image=image)
imageLabel.pack()
# The entry box widget
inputBox = tk.Entry(root)
inputBox.pack()
# The button widget
button = tk.Button(root, text='Submit', command=getText)
button.pack()
tk.mainloop()
Here is the reference if you want to know more about the Tkinter Entry Widget: http://effbot.org/tkinterbook/entry.htm
Reference on how to get the image: Stackoverflow Question

Categories

Resources