Don't focus Python subprocess, linux - python

I'm running a script in a console to help me in a repetitive task.
I want open image in gallery and write down numbers from an image.
feh = subprocess.Popen(['feh', 'tmp.jpg'])
print ("Input number from image:")
number = input()
feh.kill()
This code works, but window managers keep focusing feh, which adds an additional step of refocusing console window. Is there an additional argument I can pass to prevent this behavior or another way around?

One dirty workaround is to simply refocus window by mouse.
I used xdotool
feh = subprocess.Popen(['feh', 'tmp.jpg'])
time.sleep(0.1)
subprocess.call(['xdotool', 'click', '1'])
something = input()
feh.kill()

Python has native GUI modules, named tkinter.
GUI program can be terrifyingly easy to write, if it is python.
#!/usr/bin/python2 -i
from Tkinter import *
from PIL import *
import os
files = [f for f in os.listdir('.') if f.endswith(".png")]
root = Tk()
label = Label(root)
label.pack()
for name in files:
im = PhotoImage(file=name)
label.config(image=im)
print("your number plz")
input_str = raw_input()

Related

Why the tkinter function automatically repeats twice?

When I try to build a simple UI, everything works well, except the tkinter function I used always repeats twice, I am not sure why this happens and how to deal with it. Here is an example code:
import tkinter as tk
root = tk.Tk()
dirname = tk.filedialog.askdirectory(parent=root, initialdir="/",title='Please select a directory')
print(dirname)
When I run this code, the function works well, it will let me select a folder, but after I select the folder, it asks me to select it again. And from the print(), it outputs both the folders I have selected.
What should I do to make it only run one time?
Hi can you try with below script, I tried running below script and it does not ask for second selection and dont print second selection as well;
import tkinter as tk
from tkinter import filedialog as fd
root = tk.Tk()
dirname = fd.askdirectory(parent=root, initialdir="/",title='Please select a
directory')
print(dirname)

How to fix Tkinter dead frezzing or crashing because of huge data?

I am trying to make a program to display one single image (.png extension) at once but giving a button to the user to change the picture.
What I have done is:
Reading the Image from my directory with help of Pillow module
Appended it to a list
With a button I increase or decrease the index of the list.
(Note I have to read 600 images approx.)
Here's the code:
import os
from tkinter import *
from PIL import ImageTk,Image
import threading,time
#Define the tkinter instance
x=0
win= Tk()
dir_path= os.path.dirname(os.path.realpath(__file__))
print(dir_path)
l1=[]
#Define the size of the tkinter frame
win.geometry("700x400")
def start():
threading.Thread(target=bg).start()
win.after(5000,threading.Thread(target=fg).start())
#Define the function to start the thread
def bg():
print("bg")
for i in range(1,604):
a=Image.open(f"{dir_path}\\{i}.png")
a=a.resize((500,700), Image.ANTIALIAS)
b=ImageTk.PhotoImage(a)
l1.append(b)
print(b)
print(len(l1))
def fg():
def add():
global x
x+=1
img2=l1[x]
d.configure(image=img2)
d.image = img2
d.update()
global d
d=Label(win,image=l1[x])
d.pack()
Button(win,text="add",command=add).place(x=0,y=0)
label= Label(win)
label.pack(pady=20)
#Create button
b1= Button(win,text= "Start", command=start)
b1.pack(pady=20)
win.mainloop()
But the problem is that the Tkinter gets dead freeze and laggy to an extent that the GUI is not operable.
So my question is,
How to fix Tkinter dead Frezzes and if there is any way to read the images as fast as possible?
The freezes of Tkinter depends on reading speed of the interpreter, because:
continuously reading and Showing the pictures are a huge job for Python.
reading images using opencv or any other image processing module wont help as reading part can become faster, but showing the image in tkinter is done using python only, so rapid changes in Label will cause tkinter to crash.
Solution:
Switch to a different compiler based language for example c++.
this solution is specifically for a image slideshow,
The solution is to use selenium with python. You can specify the image location in driver.get(image_path) and it will open the image for you, and if you want to change the image with a button, then just rename all your images with the numbers and make a button to add +1 to the index.

make python file as executable file. modules: tkinter, pandas

import pandas as pd
from tkinter import *
from tkinter import filedialog
def final():
Tk().withdraw() # Close the root window
in_path = filedialog.askopenfilename()
print(in_path)
df = pd.read_csv(in_path)
newList = df['delivery_price'].tolist()
print(newList)
output = list(map(lambda elem: float(elem.split()[0]), newList))
print()
print("Your total amount is: " + str(sum(output)))
button.destroy()
label = Label(root, text="Your total amount is \n" + str(sum(output)))
label.pack()
root = Tk()
button = Button(root, text="Find total", command=final)
button.pack()
button.place(relx=0.5,rely=0.5,anchor=CENTER)
root.title("Sherpa")
root.geometry('200x200+600+250')
root.mainloop()
I wrote this small program which extracts a specific column from a CSV file which the user chooses.
the column consists of text and float:
"AUD 31.33"
Then, it gets rid of the string, and save it as the only float in a list.
In the end, I get the total amount of the column.
I used TKinter for the gui:
when I run it in pyCharm:
1) a small window appears with a button "find total"
2) after clicking "find total", it ask for the .csv file
3) user chooses the file.
4) the total amount is displayed in the small window.
That's what I really wanted with the program. but now I want to make it .exe so that I don't have to open pycharm all the time.
I tried py2installer, it gets compiled but it doesn`t run. Is there any format to follow to make GUI apps that are executable.
Or do I have to make changes in my code?
Can you see what the error is that you get? (Sometimes difficult with exe-files, because the window closes after the error. I sometimes try to make a screenshot at the right moment).
I had a problem with the PyQt module when compiling a script with Tkinter using pyinstaller. What worked for me was the solution mentioned here. It's copying the qwindows.dll file to the directory \platforms\qwindows.dllin your pyinstaller output dir (..\dist\<your program.\platforms\qwindows.dll).

Tkinter askopenfilename() won't open

I have a selection of excel data that I am analyzing, and have just recently added the ability for the user to open the file explorer and locate the file visually, as opposed to entering the file location on the command line. I found this question (and answer) to make the window appear, which worked for a while.
I am still using the command line for everything except locating the file. Currently, this is a skeleton of what I have to open the window (nearly identical to the answer of the question linked above)
Tk().withdraw()
data_file_path = askopenfilename()
# other code with prompts, mostly print statements
Tk().withdraw()
drug_library_path = askopenfilename()
Once the code reaches the first two lines of code, the command line just sits with a blinking cursor, like it's waiting for input (my guess, for askopenfilename() to return a file location), but nothing happens. I can't ctrl+C to get out of the program, either.
I have found this question, which is close to what I'm looking for, but I'm on Windows, not Mac, and I can't even get the window to open -- most questions I see talk about not being able to close the window.
Thanks for any help!
Note: At this point in the program, no data from excel has been loaded. This is one of the first lines that is ran.
Try easygui instead. It's also built on tkinter, but unlike filedialog it's made to run without a full GUI.
Since you are using Windows, use this command in the command line (not in python) to install easygui:
py -m pip install easygui
then try this code:
import easygui
data_file_path = easygui.fileopenbox()
# other code with prompts, mostly print statements
drug_library_path = easygui.fileopenbox()
If you want to use an internal module, you can import tkFileDialog, and call:
filename = tkFileDialog.askopenfilename(title="Open Filename",filetypes=(("TXT Files","*.txt"),("All Files","*.*")))
I use this in many projects, you can add arguments such as initialdir, and you can specify allowable filetypes!
I had the same problem, but I found that the issue was that I was getting input with input() before I called askopenfilename() or fileopenbox().
from tkinter import Tk
from tkinter.filedialog import askopenfilename
var = input()
Tk().withdraw()
filepath = askopenfilename()
I simply switched the positions of askopenfilename() (or fileopenbox()) and input(), and it worked as usual.
Tk().withdraw()
filepath = askopenfilename()
var = input()

How can I run a python code opening a Tkinter window and not a shell's one?

This is my first question.
I have a python program that recognize voice and reply with voice.
I wish to add a little GUI for my program (it should have only an image on background and a button to quit the program)
I would like that when I launch my code from terminal, it opened a Tkinter window and at the same time the python program start.
I’m working on Mac Os.
I use speech_recognition package to recognize voice and I use NSS speaker to let my computer speak.
This is a example of my code:
import speech_recognition as sr
from AppKit import NSSpeechSynthesizer
#VARIABLES
L = sr.Recognizer() #LISTENING
nssp = NSSpeechSynthesizer #SPEAKING
S = nssp.alloc().init()
while True:
audio = L.listen(source)
s = L.recognize_google(audio, language="en-US")
if s == "hi":
S.startSpeakingString_("Hello!!!")
Where do I have to write the Tkinter instructions to make sure that when I run my code it opens only a Tkinter window (while my program goes on) and not a shell's one?
You'll find it difficult to introduce your GUI as your code has already been written, note that everything in Tkinter has to be stored in some sort of Label or Widget and so you can't just print what you already have onto the Tkinter screen.
Here is some code to create a basic Tkinter window. Try searching online and playing around with how to present your variables within said window
import tkinter
from tkinter import *
root = tkinter.Tk()
root.configure(background = "#66ffdd") #here you can use any hex color code or just leave it blank and configure as default
root.title("Voice Program") #use the name of your program (this is the window header/title)
root.geometry("800x500") #these are your window dimensions
welcome = tkinter.Message(root, text = "Welcome to my program")
button = tkinter.Button(root, text="This button", command=print("hello")) #here insert a function for the button to perform i.e quit
welcome.pack()
button.pack() #packing presents your variables to the window - you can also use other geometry managers like grid
This site is really useful for showing you what widgets are available and what you can do with them - try searching any issues or posting a more specific question in the future if you struggle.
http://effbot.org/tkinterbook/button.htm

Categories

Resources