Empty Lines Printing After Using a GUI in Python - python

The following is something that began happening within the past three (3) months (written March 10, 2021):
Whenever I run a GUI, either using Qt or tkinter in Python, the interpreter window from which I executed the function will begin sending line feeds to the console and will not start until I quit() the interpreter.
1. Code Examples to Reproduce Problem
1a. Qt
from PySide2.QtWidgets import QApplication, QFileDialog
if QApplication.instance():
app = QApplication.instance()
else:
app = QApplication([])
filename = QFileDialog.getOpenFileName()
...OR...
1b. Tkinter
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
...OR... any usage of tkinter or Qt, then the console in which I am working will continue to print line feeds every 30 seconds (I timed it).
The resultant appearance of the console is something like this:
In[3]: filename = QFileDialog.getOpenFileName()
In[4]:
prin
t("Hello wor
ld")
In[4]: print("Hello world")
Hello world
Due to this, I would say that perhaps, "line feed", isn't the best description, as the interpreter is not reading any '\n' characters
2. Environment Info
I am currently running MS Windows 10 Enterprise (for work)
Python version: 3.9.2
I am pretty sure it was happening at least as soon as a installed 3.9.0, but not sure
I can reproduce this while running from a DOS command prompt (i.e. python run_gui_test.py) and as long as the GUI is open, it will print the line feeds
I can reproduce this from Anaconda virtual environment (conda 4.9.1 with python 3.7.9)
I can reproduce this running from a normal Python interpreter
I can reproduce this running from an iPython interpreter (7.20.0)
Also worth mentioning, I currently suppress the Qt warning related to screen ratios
This was happening before I suppressed the warnings and afterwards.
3. One Exception
It does not occur from within the Spyder iPython console (iPython 7.19.0, python 3.7.9)
Seeing how I do most of my debugging in an iPython console, it gets really annoying after a while.

Related

Change IDLE Shell window title

I'm using multiple instances (idle/shell) of python and they both have the same title ('Python 3.8.1 Shell'). How I can change it directly from python shell?
Os Windows.
I tried, but this is not helped me:
import ctypes
ctypes.windll.kernel32.SetConsoleTitleA("My New Title")
also tried:
>>> from os import system
>>> system("title " + 'abc')
Screenshot that demonstrates a same titles
for python 3
import ctypes
ctypes.windll.kernel32.SetConsoleTitleW("My New Title")
For python 2:
import ctypes
ctypes.windll.kernel32.SetConsoleTitleA("My New Title")
Edit
Try this code:
>>> import sys
>>> sys.stdout.write("\x1b]2;test\x07")
Where in place of test, put your name you want
Edit 2
Added screenshot for confirmation
I am also using Windows See
IDLE intentionally isolates its GUI, including Shell, from the running of your code. By default, they run in separate processes. If you start idle with 'python -m idlelib -n' so that GUI code and your code run in the same process, you might possibly break out of the within-process sandbox and change the window title. If you were to do so and said how, I might consider it a bug to be fixed.
What you can do from outside IDLE, is outside IDLE's control, and likely system dependent.
IDLE has a '-t title' startup option. python -m idlelib -t My-shell starts IDLE with a shell entitled "My-shell". To have a space in the title (and perhaps other chars, depending on the system), as with "My shell", quote it on the command line. On Windows, use double quotes, as I just did. I hope that this meets your need.
We could add 'Change title' to the Shell menu. But AFAIK you are the first to request this ability, and the IDLE charter is to keep it reasonably simple.

TKinter (filedialog.askdirectory) freezing Spyder console

I noticed in other questions that there are (or were) several problems with TKinter in Spyder. I have been using it in IDLE for a while but I am moving to Spyder, and came upon some problems.
I am running Python 3.6.4 with Spyder 3.2.8 from Anaconda 1.8.4, on Windows 7 Enterprise.
When I try to use some TKinter functions (like filedialog.askdirectory) Spyder´s console freeze.
I´ve been reading different forums but still no one has the same problem or a solution to this problem.
Here is a simple code that would work in IDLE, but not in SPYDER:
import os
from tkinter import Tk, filedialog
Tk().withdraw()
print("Done WITHDRAW")
currentdir= os.getcwd()
print("Done GETCWD")
filename= filedialog.askdirectory(title="Select folder", initialdir=currentdir)
print("Done ASKDIRECTORY")
As a result, I get:
runfile('M:/Users/KPK2/.../hello.py', wdir='M:/Users/KPK2/...')
Done WITHDRAW
Done GETCWD
And the console keeps running, waiting for the ASKDIRECTORY to pop a new window to select a file. In IDLE it works just fine.
Does anyone know which could be the problem and some possible solution?
I read on other threads solutions like updating to Spyder 3.0 (I already have 3.2.8) or changing some "External Modules" for the "Console" in Preferences, but there is not such a tab on my Prefereneces window (don´t know how to do that otherwise).
Thank you.
try running this command %gui tk at the console before running your code.
The alternative is it go to Tools > Preferences > IPython Console > Graphics > Graphics backend and select tkinter there.
This worked for me :)
The answer was found here https://groups.google.com/forum/#!topic/spyderlib/rFJhJZgjZTE

Kivy, how to disable console

I'm coding some software with python and kivy and want to disable the command window, that opens up in window side by side with the kivy app.
I entered that command in the command window to call the python prog:
python main.py -m console
From now on, I can click once at any kivy widget on the bottom side of my app. Then there is that console showing in the picture below. I can disable it by pressing STRG+E twice (activate, then deactivate).
The bad thing, this console part is there with every program start out of eclipse, direct call by python main.py or also in the compiled version, compiled with pyinstaller.
I tried to reinstall whole python on my system, but it doesn't work.
How can I disable this console thingy?
If you're packaging your app with PyInstaller, you should take a look at the --noconsole command line option. It should get rid of the console in Windows and OS X:
Windows and Mac OS X: do not provide a console window for standard i/o. On Mac OS X this also triggers building an OS X .app bundle. This option is ignored in *NIX systems.
import sys
if sys.platform=="win32":
import ctypes
ctypes.windll.user32.ShowWindow( ctypes.windll.kernel32.GetConsoleWindow(), 0 )

Cannot run PySide Qt program inside PyCharm IDE. Have to run from shell using pythonw or python.app

I made a simple 'pst.py' (hello world) program inside Pycharm. When I run it, it crashes with:
Qt internal error: qt_menu.nib could not be loaded. The .nib file
should be placed in QtGui.framework/Versions/Current/Resources/ or in
the resources directory of your application bundle.
Inside PyCharm, from an Python Console, all the modules look available:
>>> print(PySide.QtCore.qVersion())
4.7.4
>>> print(PySide.__version__)
1.1.2
So I went to the terminal and tried running the same program from the command line using 'python.app' and 'pythonw.' The program worked fine using both python.app and pythonw If I used just python pst.py, I got the same crash.
vt102:dBaseProject sloter$ python.app pst.py
vt102:dBaseProject sloter$ which python.app
/Users/sloter/anaconda/bin/python.app
vt102:dBaseProject sloter$ pythonw pst.py
vt102:dBaseProject sloter$ which pythonw
/Users/sloter/anaconda/bin/pythonw
I think that PyCharm IDE is using the same path (Users/sloter/anaconda/bin/)
I watched a youtube video where a guy wrote a very similar program inside PyCharm and then ran inside Pycharm and things worked fine.
So any ideas what I need to change to enable me to develop PySide/QT program entirely inside PyCharm?
Thanks
ps here's the code for 'pst.py' that I tried to run
#!/Users/sloter/anaconda/bin/python
# Import PySide classes
import sys
from PySide.QtCore import *
from PySide.QtGui import *
# Create a Qt application
app = QApplication(sys.argv)
# Create a Label and show it
label = QLabel("Hello World")
label.show()
# Enter Qt application main loop
app.exec_()
sys.exit()
Qt internal error: qt_menu.nib could not be loaded. The .nib file should be placed in QtGui.framework/Versions/Current/Resources/ or in the resources directory of your application bundle.
One way to get you going would be this:
mkdir -p application.app/Contents/Frameworks/QtGui.framework/Versions/Current/Resources/
cp -r $(QTLIBDIR)/QtGui.framework/Versions/4/Resources/qt_menu.nib application.app/Contents/Frameworks/QtGui.framework/Versions/Current/Resources/
In general, I would personally suggest to use macdeployqt if you happen to copy these manually.

PySide Qt script doesn't launch from Spyder but works from shell

I have a weird bug in my project that uses PySide for its Qt GUI, and in response I'm trying to test with simpler code that sets up the environment.
Here is the code I am testing with: https://stackoverflow.com/a/6906552/130164
When I launch that from my shell (python test.py), it works perfectly. However, when I run that script in Spyder, I get the following error:
Traceback (most recent call last):
File "/home/test/Desktop/test/test.py", line 31, in <module>
app = QtGui.QApplication(sys.argv)
RuntimeError: A QApplication instance already exists.
If it helps, I also get the following warning:
/usr/lib/pymodules/python2.6/matplotlib/__init__.py:835: UserWarning: This call to matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
Why does that code work when launched from my shell but not from Spyder?
Update: Mata answered that the problem happens because Spyder uses Qt, which makes sense. For now, I've set up execution in Spyder using the "Execute in an external system terminal" option, which doesn't cause errors but doesn't allow debugging, either. Does Spyder have any built-in workarounds to this?
As Spyder also is a Qt application, it starts it's own QApplication. In the same process only one QApplication can exist, that's why you get the first error.
Sypder also uses matplotlib, and probably, therfore it already will have imported some of the mentioned modules, so that's why you get the second error.
So when usin it like that, you can't create your own QApplication or call matplotlib.use(). Or maybe it will work if you wrap these calls in try/except.
I have the same problem, and somewhere on stackoverflow was a solution.
Instead of
qApp = QtGui.QApplication(sys.argv)
Use
qApp = QtGui.QApplication.instance()
if qApp is None:
qApp = QtGui.QApplication(sys.argv)
It won't work in Spyder if you try to launch the application into an interactive console because that console is specially configured to import several scientific libraries, automatically show() matplotlib figures, and a few other details. Type scientific at the Spyder console prompt for more details. The result is effectively that a Qt application event loop is already running there.
To get your application to run inside of Spyder:
Make sure Spyder is configured to open external consoles with PySide and not PyQt. This can be set from Tools>Preferences>Console>External modules>Qt-Python bindings library selection.
With your script active in the editor, hit F6 to open the Run Settings dialog. Select the "Execute in a new dedicated Python interpreter" radio button instead of executing in the current interactive interpreter. Click OK. Now run the script by hitting F5. Debug the script by hitting Ctrl+F5.
The official Spyder wiki has a page on the subject: https://github.com/spyder-ide/spyder/wiki/How-to-run-PyQt-applications-within-Spyder. The gist of it is:
Important Note: Before running a PyQt application in Spyder, you need to change your Graphics backend to Automatic. You can do that by going to
Tools > Preferences > IPython Console > Graphics
After that, please restart your console kernels or Spyder itself for this change to take effect.
There's an explantion at the end:
The most common problem when running a PyQt application multiple times inside Spyder is that a QApplication instance remains in the namespace of the IPython console kernel after the first run. In other words, when you try to re-run your application, you already have a QApplication instance initialized.
Trying to remove that instance will probably cause your program to get stuck in a blocking while-loop, as suggested here, and using sys.exit() doesn't help since it's the same as trying to exit Python (and hence the IPython console).
A suggested solution is doing something like what #mata suggsets.

Categories

Resources