So I'm playing around with some code and I'm trying to design a program that displays an image if a true statement results from the input. An example would be as follows:
name = input('name: ')
if name == 'Sammi':
# Here is where I would put the command to open an image. In place of print or whatever.
# I need some help with exactly what function to put here though.
The idea is that if the input string matches 'Sammi', then an image of me will be displayed preferably in a separate window, but I'm not exactly sure if that's possible or practical.
I've seen some guides that use PIL but the process of downloading and installing the required software is really tedious and I just have to wonder if it is actually required. I primarily use PyCharm for my code and occasionally ill go over to Notepad++ but it's mostly PyCharm. I'm not sure if that information is helpful but I thought I would provide it.
The image I want to use is located on my desktop and ideally would use the path C:\users\sammi\OneDrive\Desktop\B&W_2.jpg
My question as stated before is: exactly what function will allow me to do this? When you answer I would also really appreciate it if you explain the purpose of certain operators like fromand or for example, or whatever other operators or functions are used. I'm still fairly new to this stuff but I want to get really good at it.
Short reply, if you are running Python from the Standard Library, you can't, directly. The Standard Library is mostly a back-end library, so it works with logic, but doesn't "show" anything. This means that there's no way with the Standard Library to show images, you can however launch a process which opens the images.
E.g. Microsoft Paint
import subprocess
def open_image(path:str) -> None:
command = f'mspaint {path}'
subprocess.Popen(command)
open_image(input('Type your path: '))
If you don't want paint or another application, you should find a library that does it, be it Pillow or others.
To do this "right", you will need to learn about GUI programming with a library such as tkinter. Otherwise, the quick and dirty way is to use Image.show() from PIL. The documentation states that this is only intended for debugging purposes, so you should avoid it as a permanent solution in a serious project.
First of all, it is a good thing to know how to install packages (the things you can import in your scripts to use functions others made). It will be usefull when doing more complicated projects.
In Pycharm, you can add packages to your project:
File -> Settings -> Project: Project_Name -> Python Interpreter
Clicking on the + icon and searching pillow
This is not really used because there are better ways of installing packages
These are the two main ways of installing packages:
Using pip (https://pip.pypa.io/en/stable/installation/)
Using conda (https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html#regular-installation)
Both of these allow you to install packages.
I would recommend using conda because it is easier to separate projects from one another and allows the installation of packages that are not available using pip.
You will then be able to install PIL in the command line using
pip install Pillow
or (conda requires more setup, I encourage you to read https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html)
conda install -c anaconda pillow
After installing the package you want here pillow, you can then use it in your code:
from PIL import Image
#from is used to specify the package to import
#import is used to specify which module you want to import in that library.
#The module contains functions you can use. (It's more complicated than that, but for basics this is what is does)
name = input('name: ')
if name == 'Sammi':
im = Image.open("sample-image.png") #Open the image
im.show() #Show the image on screen
If you prefer to avoid using any PyPi you can use tkinter.
# As to not to pollute the namespace, from module 'tkinter' only import these classes, and make it
# so you don't have to type tkinter.Whatever() every time you want to have a class instance
from tkinter import Tk, PhotoImage, Label
# Allow for case-insensitive inputs.
if input('Name: ').casefold() == 'sammi':
# Initialize graphical window instance
window = Tk()
window.title("StackOverflow Example")
# Load the image
image = PhotoImage(file=r"C:\users\sammi\OneDrive\Desktop\B&W_2.jpg")
Label(window, image=image).pack()
# Bring the window to the front once it appears
window.lift()
window.attributes('-topmost', True)
window.after_idle(window.attributes, '-topmost', False)
# Make window appear with all parameters set as described above
window.mainloop()
Related
import time
import subprocess
from pyvda import AppView, get_apps_by_z_order, VirtualDesktop, get_virtual_desktops
#clockify
subprocess.Popen("C:/Program Files/Clockify/ClockifyWindows.exe")
current_window = AppView.current()
target_desktop = VirtualDesktop(7)
current_window.move(target_desktop)
VirtualDesktop(7).go()
trying to load specific programs to specific desktops in windows 11; so, my "clockify" app loads on the desktop "clock" and blender loads on the blend desktop so on so on.
cannot find any docs for this mofo, but pieced together what's above.
it would be awesome to:
a) check if a virtual desktop exist, and create it, incase of accidental deletion.
but really what I need is a way to specify the "current window". right now (i'm assuming python sees the that as whatever window is active as the current window); I have to put the sleep timer inbeteen loading programs, which is fine.
b) need a way to specify what window as active, then i can tie that to the appropriate desktop and maybe load them all at once to save time
#still a newb and no formal training. and alot of aconyms confuse me, and obvious assumptions may not be obvious to me.
cheers,
-mda
I need to create a dialog box that allows user to select one option from a list in Python on Windows using PyWin32 library. PyWin32 has a DialogBox function, but I cannot find any examples how to use it and I never used it before. Could anybody give me some advice?
The window should be something similar to the one below - this has been created using Zenity (scroll bar is unneeded, this has been added by Zenity itself; I'm perfectly fine with a window that just lists the options - there will be no more than about 5-6 of them), but I would rather like to avoid using external tools like Zenity, I also cannot install other libraries on the system except PyWin32 that is already installed.
Have to reply to myself :). Within the directory where PyWin32 is installed, there is a file pythonwin\pywin\dialogs\list.py that contains a sample class ListDialog implementing exactly such a dialog. It can be either used directly "as is", with some code like following:
import pywin.dialogs.list
result=pywin.dialogs.list.SelectFromList('Select level', ['standard', 'advanced', 'expert'])
print(result)
or it can be copied to a separate file and modified to change the style/layout/behavior of the window and imported from the modified file.
Does anyone know the trick to pywinauto's find_window function? I am building an application with kivy, and trying to use pywinauto to bring an .exe to the foreground, using the following code:
SetForegroundWindow(find_window(title='program.exe'))
I simply want to identify a currently open .exe, and bring it to the foreground. I have looked here https://pywinauto.github.io/docs/code/pywinauto.findwindows.html and it seems "title=" is what I want.
Does anyone know how to point to the .exe with pywinauto?
I think title is for window title (i.e. "python - Cannot find..." in case of this tab), are you sure it not more like "process='program.exe'" ?
if it needs to be and int then its pid (process id) and you can use this to get process id by title:
import win32gui,win32process
def get_window_pid(title):
hwnd = win32gui.FindWindow(None, title)
threadid,pid = win32process.GetWindowThreadProcessId(hwnd)
return pid
Eventually have at this answer as it contains really nice class for getting windows Python Window Activation, i dont want to copy paste, but use it and then you can do:
w = WindowMgr()
w.find_window_wildcard(".*Hello.*")
w.set_foreground()
find_window is low level function I wouldn’t recommend to use.
The right thing is Application object connected to the target process. It can be used so:
from pywinauto import Application
app = Application(backend=“uia”).connect(path=“program.exe”)
app.WindowTitle.set_focus()
If you have several app instances, there is a Desktop object to walk all the windows in the system:
from pywinauto import Desktop
Desktop(backend=“win32”).window(title=“Window Title”, found_index=0).set_focus()
You referred to the old docs for version 0.5.4, the latest one is 0.6.4 with two backends available and many bug fixes. The Getting Started Guide link on the main page is a good source to learn the main concept.
I’d like to create a restricted folder/ file explorer in Python (I have version 2.7.9, but I don’t mind changing that) for Windows.
Essentially, I want to initially specify the folder to which the code opens. For example, the code should initially open to: C:\Users\myName\Desktop\myDemoFolder (the user must not know this folder simply by looking at the GUI).
The user must be able to browse downwards (deeper into folders) and backwards (but only up to the initial folder to which the code opens). The user must be able to click to open a file (for example: pdf), and the file must automatically open in its default application.
An example of what I’d like is presented in figure 1. (The look of the interface is not important)
Currently, I am able to get figure 2 using the code presented here:
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
print(filename)
Research has indicated that it is not possible to change the default buttons in Tkinter windows. Is this true? If it can’t be done with Tkinter (and that’s fine), how else can we do it?
I’d happily choose simple, non-Tkinter code (perhaps using wxPython’s wx.GenericDirCtrl()) rather than elaborate Tkinter code, but no restrictive libraries please.
A modular design approach is not needed. I’d rather have simple (functional) code that is shorter than object-oriented code.
I was trying to do the same thing when I realized that maybe you could create all the buttons you need and then set the color of the buttons you don't need to your background color using:
button-name.config(bg = "background-color")
Just change the "button-name" to your button's name and set "background-color" to the background color!
I saw that post (that is really helpful : Take a screenshot via a python script. [Linux]) about taking a screenshot from python. It works well but I'd like to have the same behavior as gnome-screenshot : having the possibility to choose between :
Capturing the whole desktop
Capturing an active window
Capturing an area
Is there a way to do this in python, or, eventually, to use the gnome-screenshot application to do it, and then getting the file ?
I tried to find the perfect command line for gnome-screenshot to be launched without asking where to save the screenshot after by giving the path at the call, but I can't find it.
Thanks for your help!
I have a wrapper project (pyscreenshot) for scrot, imagemagick, pyqt, wx and pygtk.
If you have one of them, you can use it.
Capturing an active window is missing.
Install:
easy_install pyscreenshot
Example:
import pyscreenshot as ImageGrab
# fullscreen
im=ImageGrab.grab()
im.show()
# part of the screen
im=ImageGrab.grab(bbox=(10,10,500,500))
im.show()
# to file
ImageGrab.grab_to_file('im.png')
If you are not limited to using using gnome-screenshot specifically, ImageMagick's import command can save directly to file without an interactive prompt.
See here for details: http://www.imagemagick.org/script/import.php
In addition to the command line interface, there is also a Python API.