How to Python tkinter image insert relative path method - python

There's something I want to make, so I'm learning tkinter.
The relative route is not recognized.
Example code.
Suppose that hyunju.png is in the corresponding .py folder.
import tkinter
root = tkinter.Tk()
root.title("tk")
canvas = tkinter.Canvas(root, width=400, height=600)
canvas.pack()
gazou = tkinter.PhotoImage(file="hyunju.png")
canvas.create_image(200, 300, image=gazou)
root.mainloop()
tkinter.TclError: couldn't open "hyunju.png": no such file or
directory
I'm having a hard time because if I use Copy path, there will be a problem when I share or change files.
The editor used is VS code and OS is window 10.
help for me thank you

Depending on hardcoded relative paths should be avoided in this scenario, as they're often times unreliable. Depending on your IDE and even OS it may work or not.
Thus, You should choose a more dynamic better an approach like the following:
import pathlib, os
img_file_name = "hyunju.png"
current_dir = pathlib.Path(__file__).parent.resolve() # current directory
img_path = os.path.join(current_dir, img_file_name) # join with your image's file name
As long as the image file is guaranteed to be in the same directory as the script being executed, it does not matter what IDE / OS you're on - it will work.

I had the same problem and I don't know if it might be the same case for you, just check that you are opening the whole project and not just the .py file if you are working on an IDE like, for example, Visual Studio Code, because else it won't be able to find any relatives paths

Related

How to add icon into toolbar QAction [duplicate]

I'm currently using QT designer to show a picture on my loading screen.
It should look like this:
However, it looks like this:
This is because for some reason its not showing my picture, when it registers in my IDE that the filepath is correct as seen here:
The only time the picture actually shows in my loading GUI is when I use the FULL file path which is: C:\Users\myalt\OneDrive\Desktop\GUINEW\assets\PostmonkeyLogo.png
But of course, this is not viable when this software will be used on many different computer with different file paths.
self.label.setPixmap(QPixmap(u"assets/PostmonkeyLogo.png")) ## image file path to show
The problem is that the file path is relative to where the console was opened and the python.exe command is executed. It is better to build the full path using the information as the path of the .py:
import os.path
# ...
CURRENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(CURRENT_DIRECTORY, "assets/PostmonkeyLogo.png")
self.label.setPixmap(QPixmap(filename))

Why does asksaveasfilename not return the file type?

Tkinter is a great package and filedialog has some very helpful features. Both askopenfilename and asksaveasfilename have the 'filetypes' attribute, but it works differently for each one.
With askopenfilename it provides options in the GUI and returns the filetype, BUT
with asksaveasfilename it only provides options in the GUI and does not return the filetype. Example code is shown below:
import tkinter as tk
from tkinter import filedialog
old_file_name = filedialog.askopenfilename(title = "Choose file",filetypes=\
(('All files','*.*'),\
('tagData','*.tagData'),\
('FDAX files','*.fdax'),\
('CSV files','*.csv')))
new_file_name = filedialog.asksaveasfilename(initialdir = "/",filetypes=\
(('tagData','*.tagData'),\
('FDAX files','*.fdax'),\
('CSV files','*.csv'),\
('XLS files','*.xls')))
print(old_file_name)
print(new_file_name)
Output:
C:/Users/christian.abbott/Desktop/FDAX_Error/example.csv
C:/Users/christian.abbott/Desktop/example
I have looked for good filedialog documentation but have not been able to find it. Why does the package behave this way? Is there a better option to extract the full path of a user-prompted file path?
I had this same problem with Python 3 on Windows 10. I managed to solve it by removing the * before the period in the file types tuples. The following change should, hopefully, do what you want:
new_file_name = filedialog.asksaveasfilename(initialdir = "/",filetypes=\
(('tagData','.tagData'),\
('FDAX files','.fdax'),\
('CSV files','.csv'),\
('XLS files','.xls')))
This worked for me, good luck!
This has nothing to do with tkinter. Windows file explorer hides the file extensions from you by default. So when you see a "example" file in file explorer, Windows is lying to you. The actual filename is "example.csv". Most programs (including python) do not lie, and show you the actual filename.
For entering the filename tkinter uses the OS file selection widget and just displays whatever it returns. I tested it with Win7 and it did not include the extension; however in Debian Jessie it did. If it does not you can always add some code to do it for the user:
if not new_file_name.endswith(('tagData','fdax','csv','xls')):
new_file_name += '.csv'
Search in the start menu for "show extensions" and you can turn this "feature" off.

does not show icons

I just installed Python3 (3.5.2) and Pyqt5 (5.8.2) and I am following this tutorial to learn and make a GUI: http://zetcode.com/gui/pyqt5/firstprograms/
I'm trying to run the 2nd example but program is returning an error (which also happened on the 1st one, but since it had no image i took no notice) which is the following:
QApplication: invalid style override passed, ignoring it.
No XVisualInfo for format QSurfaceFormat(version 2.0, options QFlags<QSurfaceFormat::FormatOption>(), depthBufferSize -1, redBufferSize 1, greenBufferSize 1, blueBufferSize 1, alphaBufferSize -1, stencilBufferSize -1, samples -1, swapBehavior QSurfaceFormat::SwapBehavior(SingleBuffer), swapInterval 1, profile QSurfaceFormat::OpenGLContextProfile(NoProfile))
Falling back to using screens root_visual.
What is the meaning of this? Am i missing some packages?
I installed pyqt first with this command:
sudo -H pip3 install PyQt5
but Python3 was not acknowledging its existence so i searched the apt ubuntu repos and installed with:
sudo apt install python3-PyQt5
I also tried to reference the image by full path /foo/bar/image.png and nothing
What is the problem?
EDIT #1
The code that i am using is from example 2:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
This example shows an icon
in the titlebar of the window.
author: Jan Bodnar
website: zetcode.com
last edited: January 2015
"""
import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
base_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(base_dir)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('image.png'))
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
After your post i reinstalled all my packages. The error is slightly different but the result is the same:
python3 example_02.py
QApplication: invalid style override passed, ignoring it.
Screencapture:
Notice that you are having no icons at all for all applications, not just for the PyQt icon example. This is because by default, certain environments turn off the icons in the titlebar. You have to enable them.
For instance in Xfce Desktop Environment, we can use the xfce4-settings-editor tool. In Settings/Settings Editor select xfwm4.
Find the show_app_icon option and check it. Change a theme back and forth to see the changes; they are not visible right away.
After this, you will see the icon in the titlebar of the PyQt5 example.
As for the warning; it is a recent thing and it has to do something
with the incopatibilities between Qt and GTK theming. I have not found
a solution to remove the warning so far.
So first off, you have no errors in your code. That's more akin to a warning but not even. What the following line is telling you
QApplication: invalid style override passed, ignoring it
is that your style option is invalid. If that were an error your script wouldn't run at all.
What I see right off the bat is this, you never supply a path to your image.
Now if the image is in the same root directory as the script then it should recognize said image without a path. But if you're attempting to do what I think you are it wouldn't work like that anyway. I think you're trying to create a launcher icon as well as a title bar icon, which typically goes hand in hand.
It appears to me that you've added it to Atom as some form of resource file. In which case most Ide's create a path for that file. Sometimes it's a path, other times a local url. QT its self does both when working with the QT creator.
I've never used Atom so I can't tell you how that works.
What I can say is this. you're using Linux which means .ico files are useless. I told you before linux doesn't handle icon files the same way windows does. This is most likely your problem.
So I sugesst you take a look at this
https://askubuntu.com/questions/476981/how-do-i-make-a-desktop-icon-to-launch-a-program
After you read that take a look at this if you have to https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Using_a_text_editor
Both of those links explain how to create a launcher icon for your program.
The following link will explain how to set the icon on the menu bar (title bar) in your program.
PyQt4 set windows taskbar icon
I hope this helps you out!
I study PyQt5 from author who give this question,also I have this problem that my icons can't show,I try some ways to catch it,that's what I do,hope it works!
First, it's important that you should use absolute path of the icons,for example:
self.setWindowIcon(QIcon("F:/Workspace/PyQT5-Study/images/web.png"))
but this not a good idea,so you can use second way like this:
from PyQt5.QtCore import QFileInfo
# ...
def initUI(self):
# ...
root = QFileInfo(__file__).absolutePath()
self.setWindowIcon(QIcon(root+'/images/web.png'))
# or
# import os
# current_dir = os.path.dirname(os.path.realpath(__file__))
# self.setWindowIcon(QIcon(os.path.join(current_dir, 'images/web.png')))
# ...
Last, if your icons also can't show, you should check this icon, if it's a legal icon.
In short, the normal images are unlimited so more, they can store many images and transform easily, but the icons have sure size,color kind,and more important,the icons have transparency, that means you can see the background, they have frame(not always straight). So you can use the web online tools to transform your image and try again,that really help me!
Also you should check the icon's source format, ensure you never change it, like .jpg to .png,and other. This will produce problem!
Wish you can solve the problem!
On windows be sure to use a real .ico file and a full path
iconpath = os.path.join(os.getcwd(),'qtlearning','assets','python.ico')
self.setWindowIcon(QIcon(iconpath))
I faced the exact same problem.
First things first. There is no setWindowIcon() method under QWidget or QMainWindow classes, in fact. you should be trying to set the QIcon at the Application level as follows.
app = QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon('home.png'))
Second, the icon thus created using this code does not reflect on the title of the window, instead it will reflect as an application icon as shown in the image below. the home.png
" icon for Application" in Ubuntu and not the " icon over the Window Title"
Finally, the path does not really matter, it can be an absolute path or a relative path, the system will consider either.
i just provided the full path of icon as simple as that

I can't load an image in pygame/python2.7

Can someone help me load an image? It says "error: can't open tux.jpg:
import sys, pygame
pygame.init()
size = width, height = 600,400
screen = pygame.display.set_mode(size)
tux = pygame.image.load("tux.jpg")
screen.blit(tux,(200,200)) #Displays Tux On Screen
pygame.display.flip()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:sys.exit()
Please check that you have the image file within the directory that you are working in.
Using an absolute path may also be an option, for example:
tux = pygame.image.load("C:\\path\\to\\game\\tux.jpg")
For more information, please see this answer here.
The path you entered comes out as "./tux.png", i.e. the current working directory. Either place the file at the same location as your .py file (hence the default working directory for the script) or define the path to your image file.
For game file ordering, images are often in separate directories to the game scripts, The best way to do this is the os module. os.getcwd() gives the current working directory, and can be modified to the image directory using os.path.join. e.g.
game/
game.py
images/
tux.jgp
game.py uses pygame.load(os.path.join(os.getcwd(), "images")
(or define a datapath variable at the top in the same way if using lots of images!)

Use file like objects for Tk().iconbitmap()

I am writing a program using Tkinter that is to be eventually compiled into an exe using py2exe. I want to include an icon with it for use on the windows. It will be the same one as I have packed as the icon for the exe. Is there a way to include the icon in Tkinter, either by locating the exe file or using a file-like object? I know that win32api can find the current exe file that's running, but I believe that py2exe extracts the original file to temp, and then runs it, so the original exe couldn't be found that way. I also thought of putting it in an include folder, but I don't know if the cwd would be set correctly for that. Thanks for the help in advance!
Tk images have a -data option which lets you embed the image within the code. You just have to base64-encode the image. I think the image has to originally be in the GIF format.
Here's a working example:
import Tkinter as tk
root = tk.Tk()
data = '''R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9P
T6Ai8P8A/////////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYY
fh8GIEvpoUZcmtOKAO5rLMva0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYw
YtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eTYhJDQ3woDGl7foNiKBV7aYeEkHEi
gnKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOsNYa2q7mcirC5I5Fo
fsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
'''
img = tk.PhotoImage(data=data)
label = tk.Label(image=img)
label.pack()
root.mainloop()
You can embedd the icon in the py2exe binary with the icon_resources option
setup(windows=[
{'script':'toto.py', "icon_resources": [(1, "toto.ico")]},
],
Then you can retrieve it with the windows api
import win32gui, win32api, win32con
from ctypes import c_int, windll
hicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 13), True)
and then attach to a window as long as you know his HWND.
windll.user32.SendMessageA(c_int(hwnd), c_int(win32con.WM_SETICON), c_int(win32con.ICON_SMALL), c_int(hicon))
The 13 constant used in the LoadResource has been retrieved with a tool like ResourceHacker. In ResourceHacker, it corresponds to the folder name of the icon. I don't know how it is calculated by py2exe and if there is a way to force this value.
I don't know also if there is a pure TkInter way to do that and if the icon can be used as-is in a tkinter window.
I hope it helps

Categories

Resources