I want to render an image in tkinter but I always end up with an error saying that the image (PieTalk.gif) could not be found even though the image is in the same directory as the python script (startupgui.py):
/Home/COMP3203/COMP30203-project/src/ptgui/
Here is the method where I want to render an image in a GUI. The following code is a class called startupgui.py. It consists of a constructor and a method to load the image
Constructor:
def __init__(self):
# String to decide whether to go to client or server
self.trigger = None
#-----------------------#
# Creating window frame #
#-----------------------#
self.root = Tk()
self.root.wm_title("PieTalk")
self.root.geometry('600x450')
# creating PieTalk image
self.createimage()
# creating buttons
self.createbuttons()
Method to load image:
def createimage(self):
# Creating image frame
self.imageframe = Frame(self.root, bg='light grey')
self.imageframe.place(relx=0.1, relwidth=0.8, rely=0.05, relheight=0.65)
# Creating PieTalk image
self.pietalkimage=PhotoImage(file="PieTalk.gif")
# Creating label
self.imagelabel = Label(self.imageframe, image=pietalkimage)
self.imagelabel.image = self.pietalkimage
self.imagelabel.pack()
I have used the file name only:
self.pietalkimage=PhotoImage(file="PieTalk.gif")
And I have also used the absolute path to the file:
self.pietalkimage=PhotoImage(file="/Home/COMP3203/COMP30203-project/src/ptgui/PieTalk.gif")
Unfortunately, I keep on getting the same error when I execute the script:
Traceback (most recent call last):
File "pietalk.py", line 361, in <module>
startview=sgui.startupgui()
File "/home/archit/COMP3203/COMP3203-project/src/ptgui/startupgui.py", line 66, in __init__
self.createimage()
File "/home/archit/COMP3203/COMP3203-project/src/ptgui/startupgui.py", line 33, in createimage
self.pietalkimage=PhotoImage(file="/Home/COMP3203/COMP30203-project/src/ptgui/PieTalk.gif")
File "/usr/lib/python3.4/tkinter/__init__.py", line 3387, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/usr/lib/python3.4/tkinter/__init__.py", line 3343, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "/Home/COMP3203/COMP30203-project/src/ptgui/PieTalk.gif": no such file or directory
Is there something else that I am doing wrong when I am loading the image? What else can I do to load an image?
first convert it to base64 python variable
>>> import base64
>>> with open("my_image.py","w") as f:
... f.write('my_image="""%s"""'%base64.b64encode(open("my_gif.gif","rb").read()))
...
>>> exit()
you should now have the my_image.py file there ... copy that to the same directory as your tkinter script... an now you can do
from my_image import my_image
image=PhotoImage(data = my_image)
since you are having some problems lets try and simplify it a little bit
img2base64.py
import base64,sys,os,re
assert len(sys.argv) > 2,"Error: Useage %s /path/to/image.gif outfile.py"
assert os.path.exists(sys.argv[1]),"Error Unable to find image passed in as first argument"
outfile = open(sys.argv[2],"w")
raw_binary_data = open(sys.argv[1],"rb").read()
b64_encoded_data = base64.b64encode(raw_binary_data)
varname = re.sub("[^W]","_",os.path.splitext(os.path.basename(sys.argv[1]))[0])
pyname = os.path.splitext(os.path.basename(sys.argv[2]))[0]
outfile.write("%s='''%s'''"%(varname,b64_encoded_data))
outfile.close()
print "all done please put %s in your script directory and use it as follows:"%sys.argv[2]
print "from %s import %s"%(pyname,varname)
print "image=PhotoImage(data = %s)"%(varname)
just save that and then call it
$ python img2base64.py /path/to/image.gif pyimage.py
I think at least I didnt try it ...
Inspired by previous answer:
import base64
from pathlib import Path
import sys
src = Path(sys.argv[1])
dst = src.with_suffix(".py")
with dst.open("w") as f:
data = base64.b64encode(src.read_bytes()).decode('utf-8')
f.write(f'image="{data}"')
exit()
and I tested it ;-)
Related
When testing the opening of a PDF for a larger project the code throws an error. The error emanates from the tkPDFViewer.
Any ideas?
Here is the error:
Exception in thread Thread-1 (add_img): Traceback (most recent call last):
File "C:\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run()
File "C:\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, *self._kwargs)
File "C:\Python\Python310\lib\site-packages\tkPDFViewer\tkPDFViewer.py", line 46, in add_img
pix = page.getPixmap()
AttributeError: 'Page' object has no attribute 'getPixmap'. Did you mean: 'get_pixmap'?
import tkinter as tk
from tkPDFViewer import tkPDFViewer as pdf
print('Starting TestPDF2')
mainWindow = tk.Tk()
# Set the width and height of our root window.
mainWindow.geometry("550x750")
# creating object of ShowPdf from tkPDFViewer.
v1 = pdf.ShowPdf()
# Adding pdf location and width and height.
v2 = v1.pdf_view(mainWindow, pdf_location = 'testpdf.pdf', width = 50, height = 100)
# Placing Pdf in my gui.
v2.pack()
mainWindow.mainloop()
print('End TestPDF2')
This is an internal problem with tkPDFViewer. The error is quite self-explanatory - getPixmap was deprecated and removed in favor of get_pixmap in one of the dependencies of tkPDFViewer (see here). So the library needs to get fixed (the methods need to be renamed to match the new version) and it doesn't look very well maintained. You can try opening an issue or a PR on its GitHub. But I'd probably lean towards saying this library is dead and broken, and finding yourself an alternative that works.
This question already has answers here:
Changing the application and taskbar icon - Python/Tkinter
(7 answers)
Closed 1 year ago.
#MY Code
from tkinter import *
root = Tk()
root.geometry("1200x700")
root.title("MY_OS LOGIN/REGISTER")
icon=PhotoImage("C:\\Users\\Malay\\Desktop\\Main\\malay\\Python Scripts\\My OS GUI\\favicon.ico")
root.iconphoto(True,icon)
#Error I'm facing
Traceback (most recent call last):
File "C:\Users\Malay\Desktop\Main\malay\Python Scripts\My OS GUI\main.py", line 35, in
root.iconphoto(True,icon)
File "C:\Users\Malay\AppData\Local\Programs\Python\Python39\lib\tkinter_init_.py", line 2125, in wm_iconphoto
self.tk.call('wm', 'iconphoto', self._w, "-default", *args)
tkinter.TclError: failed to create color bitmap for "C:\Users\Malay\Desktop\Main\malay\Python Scripts\My OS GUI\favicon.ico"enter code here
To change the window icon in a tkinter application:
Add this piece of code
root.iconbitmap("yourimage.ico")
There appears to be two reasons this is not working. First PhotoImage does not work with the .ico file type. Second, the file name is a keyword argument, so your code should look like this.
#MY Code
from tkinter import *
root = Tk()
root.geometry("1200x700")
root.title("MY_OS LOGIN/REGISTER")
# Comment out incorrect file type
# icon=PhotoImage(file="C:\\Users\\Malay\\Desktop\\Main\\malay\\Python Scripts\\My OS GUI\\favicon.ico")
# Using keyword file and using a png
icon=PhotoImage(file="C:\\Users\\Malay\\Desktop\\Main\\malay\\Python Scripts\\My OS GUI\\favicon.png")
root.iconphoto(True,icon)
I am completely new to python.
I am trying to pass the location of Input and output using User interface as shown in this particular discussion [1]:How to give the location of "Input" and "Output" for a python code using User Interface and run the code from UI itself?
But here, I am calling an external command and trying to run it from my python code by passing location of input and output as in the above mentioned case.
from tkinter import *
from tkinter import filedialog
import numpy as np
import gdal
gdal.UseExceptions()
import os
def your_code(input_file, intermediate_file, output_file):
cmd = "gpt F:\saikiran\myGraph.xml -Psource=input_file - Ptarget=intermediate_file"
os.system(cmd)
ds = gdal.Open(intermediate_file)
band = ds.GetRasterBand(1)
……………………………………………...
#gen_map_button.place(x=230, y=300)
gen_map_button.pack()
root.mainloop()
But I encountered with this error :
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\User\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\User\GUI-pywt.py", line 145, in gen_map
your_code(input_filename, intermediate_filename, output_filename)
File "C:\Users\User\GUI-pywt.py", line 15, in your_code
ds = gdal.Open(intermediate_file)
File "C:\Users\User\Anaconda3\lib\site-packages\osgeo\gdal.py", line 3251, in Open
return _gdal.Open(*args)
RuntimeError: F:/saikiran/ddd: No such file or directory
What mistake did i do ?
Your cmd is not correct.
Concatenate string with values
cmd = "gpt F:\saikiran\myGraph.xml -Psource=" + input_file + " - Ptarget=" + intermediate_file
or use string formatting
cmd = "gpt F:\saikiran\myGraph.xml -Psource={} - Ptarget={}".format(input_file, intermediate_file)
With Python 3.6 or 3.7 you can use f-string
cmd = f"gpt F:\saikiran\myGraph.xml -Psource={input_file} - Ptarget={intermediate_file}"
Current cmd
"gpt F:\saikiran\myGraph.xml -Psource=input_file - Ptarget=intermediate_file"
will create file with name literally
intermediate_file
not
F:/saikiran/ddd
and it can make problem in gdal.Open()
I am creating a tageditor that displays the ID3-Tags of an mp3 file in a "before" "after" style in different textLines. If there's no tag available, nothing is displayed. You are also able to edit the "after" textLines and any changes made to them should be saved to the file but when I press button2 I am getting the bottom traceback. How can I save the lines6-10 as the new "audio["title"], audio["artist"]" etc? This is the GUI
import sys
import easygui
import mutagen
from mutagen.easyid3 import EasyID3
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import QLineEdit
lied = None
error = "No ID3-Tag available."
class TrackTag1(QDialog):
def __init__(self):
super(TrackTag1,self).__init__()
loadUi("TrackTag1.ui",self)
self.setWindowTitle("TrackTag")
#pyqtSlot()
def on_button1_clicked(self):
#root.fileName = filedialog.askopenfilename( filetypes = ( ("Musik Dateien", "*.mp3"), ("Alle Dateien", "*.*") ) )
#print(easygui.fileopenbox('MP3 Dateien','', '*.MP3'))
lied = easygui.fileopenbox('MP3 Dateien','', '*.MP3')
audio = EasyID3(lied)
self.line0.setText(lied) #printing filepath to line0
try:
self.line1.setText(str(audio["title"]).strip("[']")) #printing the ID3 tags after they've been stripped of "['']"
self.line6.setText(str(audio["title"]).strip("[']"))
except:
KeyError
self.line1.setText(error)
try:
self.line2.setText(str(audio["album"]).strip("[']"))
self.line7.setText(str(audio["album"]).strip("[']"))
except:
KeyError
self.line2.setText(error)
try:
self.line3.setText(str(audio["date"]).strip("[']"))
self.line8.setText(str(audio["date"]).strip("[']"))
except:
KeyError
self.line3.setText(error)
try:
self.line4.setText(str(audio["artist"]).strip("[']"))
self.line9.setText(str(audio["artist"]).strip("[']"))
except:
KeyError
self.line4.setText(error)
try:
self.line5.setText(str(audio["genre"]).strip("[']"))
self.line10.setText(str(audio["genre"]).strip("[']"))
except:
KeyError
self.line5.setText(error)
def on_button2_clicked(self):
audio = EasyID3(lied)
audio["title"] = self.line6.text()
audio.save()
app=QApplication(sys.argv)
widget=TrackTag1()
widget.show()
sys.exit(app.exec_())
app=QApplication(sys.argv)
widget=TrackTag1()
widget.show()
sys.exit(app.exec_())
I'm getting this traceback when I press the save changes button:
Traceback (most recent call last):
File "<string>", line 69, in on_button2_clicked
File "h:\program files (x86)\python\lib\site-packages\mutagen\_util.py", line 139, in wrapper
writable, create) as h:
File "h:\program files (x86)\python\lib\contextlib.py", line 59, in __enter__
return next(self.gen)
File "h:\program files (x86)\python\lib\site-packages\mutagen\_util.py", line 270, in _openfile
raise TypeError("Missing filename or fileobj argument")
TypeError: Missing filename or fileobj argument
For now, you should only be able to edit the tags but I am planning to implement a MusicBrainz query soon.
In the method on_button2_clicked the lied object is basically None.
To get the correct one, use the keyword global when assigning it in on_button1_clicked. (Which you actually never should! Instead make an attribute to store it and access it via self.lied or something similar)
Also, I am assuming that the two functions are infact class methods owing to the self keyword and you simply got the indentation wrong while copy pasting.
Basically an error due to scopes.
I'm trying to find a way how to test thumbnail generation when using Django and sorl-thumbnail's get_thumbnail() method.
Environment:
Django==1.5.5
Pillow==2.1.0
sorl-thumbnail==11.12
Simplified code under test (ran in test environment):
from StringIO import StringIO
from PIL import Image
from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db import models
from sorl.thumbnail import get_thumbnail
# simple class with ImageField
class User(models.Model):
avatar = models.ImageField(upload_to='avatars', default=None, null=True, blank=True)
def get_thumbnail_uri(self):
avatar_thumbnail = get_thumbnail(self.avatar, '100x100')
return avatar_thumbnail.url
# make sure we're using in-memory test env.
assert settings.THUMBNAIL_STORAGE == 'inmemorystorage.InMemoryStorage'
assert settings.DEFAULT_FILE_STORAGE == 'inmemorystorage.InMemoryStorage'
# prepare image
fake_file = StringIO()
picture = Image.new(mode='RGBA', size=(500, 500), color=(255, 0, 0, 0))
picture.save(fake_file, 'JPEG')
fake_file.name = 'test.jpg'
fake_file.seek(0)
uploaded_image = InMemoryUploadedFile(fake_file, field_name=None, name='test.jpg',
content_type='image/jpeg', size=fake_file.len,
charset=None)
# add image to user
u = User()
u.avatar = uploaded_image
assert u.get_thumbnail_uri() is not None
The above always fails on the last line:
Traceback (most recent call last):
File "/vagrant/path/to/file.py", line 1440, in test_stackprep
assert u.get_thumbnail_uri() is not None
File "/vagrant/path/to/file.py", line 1413, in get_thumbnail_uri
avatar_thumbnail = get_thumbnail(self.avatar, '100x100')
File "/home/vagrant/.virtualenv/appname/local/lib/python2.7/site-packages/sorl/thumbnail/shortcuts.py", line 8, in get_thumbnail
return default.backend.get_thumbnail(file_, geometry_string, **options)
File "/home/vagrant/.virtualenv/appname/local/lib/python2.7/site-packages/sorl/thumbnail/base.py", line 56, in get_thumbnail
source_image = default.engine.get_image(source)
File "/home/vagrant/.virtualenv/appname/local/lib/python2.7/site-packages/sorl/thumbnail/engines/pil_engine.py", line 13, in get_image
return Image.open(buf)
File "/home/vagrant/.virtualenv/appname/local/lib/python2.7/site-packages/PIL/Image.py", line 2008, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file
I assume that either Django or sorl-thumbnail gets out of inmemorystorage while running the test. I've been at it for a long time, but I failed to find any configuration that works, with the exception of testing stuff directly on the filesystem (which I'd like to avoid).
Did anyone manage to get sorl's get_thumbnail() method working in tests, please?
Thanks.
Version 11.12, which is the latest one on PyPI today, is 2 years old. There's version 12.0 available in repo, which should work. It's not on PyPI, because there was change of maintainers and I guess they hadn't chance to do it yet.
I've tried master version and it works ok with your example.