I need an event listener that starts and quits my script whenever I press a key. So this is a script that lets me know if a key has been pressed:
import Tkinter as tk
def onKeyPress(event):
text.insert('end', 'You pressed %s\n' % (event.char, ))
root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()
That works great but the problem is that I don't need a GUI. I should be able to press a key wherever I want. How would that be possible?
Like Rawing said, you can use the keyboard library, for example:
import keyboard
keyboard.add_hotkey('a', lambda: print "a was pressed")
Note that for this to work, the keyboard library must be installed, you can do this with $ sudo pip install keyboard
Edit: You might have to use $ sudo python -m pip install keyboard
Edit: Or you might have to use $ sudo py -m pip install keyboard
Edit: Or even $ sudo -H pip install keyboard
Also, note that I'm assuming you're using python 2.7.
Edit: if you wonder why I assumed you were using python 2.7 it was because you used from Tkinter import * in your GUI example, and in python 2.7, the tkinter module is called "Tkinter", whilst in python 3.6, tkinter is called "tkinter" so in python 3 you should use from tkinter import * (Note the lowercase "t" versus the capital "T" in tkinter/Tkinter)
Also, note that the keyboard module doesn't work on Mac (at least their pip page only says they support Windows and Linux, but it might work if you have luck)
Lastly, note that I haven't tried this myself since I currently do not have access to a computer with python installed. If it doesn't work, comment me and I'll try to find another solution :)
Edit: #RezaSaadati approved that it worked.
Related
I am new to python and I am having a problem with tkinter that no one seems to explain. I am using the
from tinker import *
and when I run the program it errors out on the
window = tk()
i have tried to install tkinter but it tells me there is a new version of pip and tells me to run python.exe -m pip install --upgrade pip in the cmd prompt. this does nothing as it errors out in
ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'i:\\python\\lib\\site-packages\\pip-22.3.1.dist-info\\entry_points.txt'
Consider using the `--user` option or check the permissions.
what am I doing wrong? please help
I have tried everything that all the web sites have explained to no avail. and a simple
from tkinter import *
window = tk()
still errors out. :(
no window pops up
Try this and see if it works as expected - I've fixed a few things based on the information you've given and the comments from other users.
import tkinter as tk # star imports are best avoided
# notice the 'tk.' namespace prefix here - this is the way to go!
window = tk.Tk() # instantiate Tk
label = tk.Label(window, text='Hello, World!') # add a widget
label.pack() # add the widget to the window
window.mainloop() # start the app
Barring that, try running this command:
python.exe -m tkinter
It should bring up a basic example tkinter app. If that works, you'll know that tkinter is at least installed correctly on your machine.
I have a tkinter GUI that allows me to start any kind of program:
# main_app.py
import tkinter as tk
import subprocess
root = tk.Tk()
cmd_entry = tk.Entry(width=50)
cmd_entry.pack(side='left')
def run_script():
sp = subprocess.run(cmd_entry.get().split(), shell=True)
run_btn = tk.Button(text="Run Command", command=run_script)
run_btn.pack(side='left')
root.mainloop()
It looks like this:
I can start another tkinter script from this window, for instance:
# dummy_app.py
import tkinter as tk
root = tk.Tk()
root.mainloop()
It even works when starting dummy_app.py with a different version of python. For example, I can start main_app.py with Python 3.10.8 and run the following:
C:\Path\to\python3.9\python.exe dummy_app.py
However, if I compile main_app.py into an executable with pyinstaller (v5.6.2):
pyinstaller.exe .\main_app.py --onefile
Then I get the following error when trying to run C:\Path\to\python3.9\python.exe dummy_app.py from main_app.exe:
C:/Users/.../AppData/Local/Temp/_MEI76562/tcl/init.tcl: version conflict for package "Tcl": have 8.6.9, need exactly 8.6.12
version conflict for package "Tcl": have 8.6.9, need exactly 8.6.12
while executing
"package require -exact Tcl 8.6.12"
(file "C:/Users/.../AppData/Local/Temp/_MEI76562/tcl/init.tcl" line 19)
invoked from within
"source C:/Users/.../AppData/Local/Temp/_MEI76562/tcl/init.tcl"
("uplevel" body line 1)
invoked from within
"uplevel #0 [list source $tclfile]"
This probably means that Tcl wasn't installed properly.
python dummy_app.py works fine however.
Why does the tcl version has to be the same when starting the script from the compiled executable? Is there a way around this?
The version of the Tcl support scripts used inside Tkinter must exactly match the version of the Tcl and Tk binary libraries used. Bugfixes may be applied in either location, but the version matching must be exact; they're matched parts a single software product.
The workaround is not to cross-match. If you bind the version in one place (e.g., with linking options) then you must bind it in the other (e.g., by shipping the script files).
We're working on making future versions (8.7 onwards) have this binding done at link time; almost all scenarios don't need significant rewriting of internal scripted parts of Tcl and Tk's implementations.
I was trying to learn GUI based python therefore i was using the Tkinter library. My OS is windows but I have installed Ubuntu wsl as my default terminal, and use wsl vscode as my default text-editor.
I was just creating a basic window using this sample code to check whether it works or not:
from Tkinter import *
def onclick():
pass
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="black", foreground="green")
root.mainloop()
Turns out it does not work with python3.8.
Terminal error message
I looked up multiple resources and forums and could not find any proper solutions. Here are couple of links i have referred to:
https://realpython.com/python-gui-tkinter/ https://tkdocs.com/tutorial/install.html https://askubuntu.com/questions/1224230/how-to-install-tkinter-for-python-3-8 .
A work around I discovered was that installed anaconda which uses python3.7 and used the windows terminal instead (using pycharm not vscode). And it looks like it is functioning properly.
GUI with python3.7
The thing is.. I like wsl and vscode far better than windows command line, and I wanted to revert back to it. Is there any solution? I really do not want to fool around with the path too much because I had a bad experience previously (But i am willing to do it again if its going to fix my problem). Thanks for hearing me out.
The problem isn't Python, but WSL. You can't run anything graphical easily inside WSL. (Microsoft is planning to add that feature, but it isn't ready yet. There are third-party solutions, but they're not that easy to set up.)
The easiest solution is to use a Windows install of Python 3.8 to run your tkinter app. You can still invoke that from inside your Ubuntu WSL, same as any Windows executable.
WSL now supports graphical interfaces. In order to use it you need to install or update WSL more info. Then run your app as usual and your program window should open.
I'm trying to build a simple Python GUI around OpenCV so I can run facial recognition commands easily. I'm using a Raspberry Pi thus Raspbian to do this
It's a case of clicking a button and an os.system command executes allowing various functions to run.
The issue is with trying to run these functions whilst in the Virtual Python Environment. I need to be inside the virtualenv to gain access to the required modules however I understand every time a os.system command is ran, a new shell is created therefore taking me out the virtual environment.
I've looked into running my functions in one os.system however I still get the import module error.
Something that i assumed would take a few mins to build is taking me days.
Any help on this would be amazing.
Thank you.
Here is my current code:
from tkinter import *
import os
from tkinter import messagebox
# creating tkinter window
root = Tk()
root.geometry('500x500')
root.title("Student Attendnace System")
def stillImage():
os.system("/home/pi/.virtualenvs/cv/bin/activate & python recognize_faces_image.py ---encodings encodings.pickle --detection-method hog --image examples/example_01.jpg")
btn3 = Button(root, text = 'Detect Faces From Image', command = stillImage)
btn3.grid(column=1, row=2)
mainloop()
The idea is to enter the virtual environment and execute another python script with added facial detection arguments.
NOTE: running this in the terminal works fine.
I would use the python from the virtualenv directly:
os.system("/home/pi/.virtualenvs/cv/bin/python recognize_faces_image.py ---encodings encodings.pickle --detection-method hog --image examples/example_01.jpg")
To elaborate a script run using a python executable from a virtualenv will look for libraries relative to the python executable, i.e. inside the virtual environment.
How do I run a .py file outside of IDLE in order to use sys.exit? I'm using command=sys.exit and seems to crash inside of tcl & tk when the button is pushed. The exit is working cause it returns SystemExit in the Shell. I've found that I need to run this outside the IDLE to have this work properly. Oh, I'm working from the book "Programming Python" tutorial. How do I run a .py(GUI) file outside of IDLE to see sys.exit work?
import sys
from tkinter import *
widget = Button(None, text='Hello widget world', command=sys.exit)
widget.pack()
widget.mainloop()
1.- In windows double click on the file.
2.- For linux, if not already there, add a shebang first, telling where python is.
Shebangs are like:
#!/usr/bin/python
or
#!/usr/bin/env python
also remember the dot-slash if you call the program from console:
./myscript.py
3.- In OSX follow same as in linux. Also see these specific instructions and these other ones