i just started to learn PyQt and GUI programing and
i copied this code exactly from the book "Rapid GUI Programming with Python and Qt:The Definitive Guide to PyQt Programming" and it supposed to show a calculator that calculates an expression.
when i run the application main window shows up but does not do anything and since i copied the code form a well known pyqt book it's very strange.
i am using python 3.4.4 and pyqt4 .this is the code i copied from book:
import sys
from math import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Form(QDialog):
def __init__(self,parent=None):
super(Form, self).__init__(parent)
self.browser = QTextBrowser()
self.lineedit = QLineEdit("Type an expression and press Enter")
self.lineedit.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
self.connect(self.lineedit, SIGNAL("retrunPressed()"),
self.updateUi)
self.setWindowTitle("Calculate")
def updateUi(self):
try:
text= unicode(self.lineedit.text())
self.browser.append("{0} = <b>{1}</b>".format(text,eval(text)))
except:
self.browser.append(
"<font color=red>%s is invalid!</font>" % text)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
these are the errors i get:
Traceback (most recent call last):
File "calculator.pyw", line 25, in updateUi
text = unicode(self.lineedit.text())
NameError: name 'unicode' is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "calculator.pyw", line 29, in updateUi
"%s is invalid!" % text)
UnboundLocalError: local variable 'text' referenced before assignment
i know its not good idea to ask someone else to debug my code but i did all i could about it and nothing came up.
thanks
You have a typo in your signal name it should be
self.connect(self.lineedit, SIGNAL("returnPressed()"),
not
self.connect(self.lineedit, SIGNAL("retrunPressed()"),
so apparently you didn't copy it well, also it seems that book was written in python2 so you don't need the unicode function strings in python3 are already unicode by default
Related
I am using PyQt5 to create two windows, main window and info window. I want to go back and forth through them, such that
initial state:
if main window is opened
I can click button info
If button info is clicked
info window is opened, main is closed
I can click main button
3.
If main button is clicked
info window is opened, main is closed
However, If I'd run the program from main window,
I'll be able to go to info, but not come back to main, through main button
Traceback (most recent call last):
File "~/Description.py", line 259, in Show_Main
Info.close()
NameError: name 'Info' is not defined
similarly, If I'd run the program from info window, I'd be able to go to main, but not back to info
Traceback (most recent call last):
File "~/M.py", line 259, in Show_Main
Form.close()
NameError: name 'Info' is not defined
This is partial code from each .py file:
M.py
from Description import Ui_Form
class Main_Form(object):
def setupUi(self, Form):
Form.setObjectName("Main")
.
.
.
def Show_Description(self):
self.DWindow = QtWidgets.QWidget()
self.ui = Ui_Form()
self.ui.setupUi2(self.DWindow)
self.DWindow.show()
Form.close()
descrpition.py
class Ui_Form(object):
def setupUi2(self, Info):
Info.setObjectName("info")
def Show_Main(self):
from M import Main_Form
self.DWindow = QtWidgets.QWidget()
self.ui = Main_Form()
self.ui.setupUi(self.DWindow)
self.DWindow.show()
Info.close()
Don't ask me why am I importing Main_Form inside the Show_Main method rather than out of it, it would return an error otherwise.
Your error message is saying that it can not recognize variable Info. From the code you've uploaded, variable Info is given to the class Ui_Form through the function setupUi2. But fucntion Show_main, the one that is creating error, does not share the variable Info that is given to the setupUi2, because it's not an instance variable. I guess you can try something like this :
def setupUi2(self,Info):
self.Info = Info
self.Info.setObjectName("info")
def Show_Main(self):
~~~
self.Info.close()
I have a dictionary where there are certain elements and associated keys. I want to create a GUI to display the items. I have used a QMessageBox PyQt widget within a for loop. But when i run the code i am getting a following error:
Traceback (most recent call last): File "C:\Python34_64bit\dictt.py", line 50, in main() File "C:\Python34_64bit\dictt.py", line 45, in main GUI=MYGUI() File "C:\Python34_64bit\dictt.py", line 31, in init self.Choice=QtGui.QMessageBox.Question(self,k,val,QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) TypeError: 'Icon' object is not callable
Kindly help me how to fix this issue with a modification to my code. Below is my code:
import sys
from PyQt4 import QtGui,QtCore
class MYGUI(QtGui.QWidget):
def __init__(self):
super(MYGUI,self).__init__()
self.setWindowTitle("GUI")
#widgets:
self.labl=QtGui.QLabel(self)
self.labl.setFont(QtGui.QFont('Calibri', 34))
#Layout:
Layout =QtGui.QVBoxLayout()
Layout.addWidget(self.labl)
Layout.addStretch()
self.setLayout(Layout)
#Actions:
Queries={'Q1':'question 1','Q2':'question2'}
for k,val in Queries.items():
self.Choice=QtGui.QMessageBox.Question(self,k,val,QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if choice==QtGui.QMessageBox.Yes:
self.labl.setText('yes')
else:
self.labl.setText('No')
self.show()
def main():
app=QtGui.QApplication(sys.argv)
GUI=MYGUI()
sys.exit(app.exec_())
main()
Your problem is just with lower/upper case.
QMessageBox.Question is the icon
QMessageBox.question(parent, title, text, button0, button1) is the function
See: https://srinikom.github.io/pyside-docs/PySide/QtGui/QMessageBox.html
I was trying to get fullscreen support for a wxPython app using the code in the answer from this stackoverflow question wxPython MacOS X Lion full screen mode
My Error
Traceback (most recent call last):
File "test_mac_fullscreen.py", line 36, in <module>
frame = Frame()
File "test_mac_fullscreen.py", line 29, in __init__
SetFullScreenCapable(self)
File "test_mac_fullscreen.py", line 16, in SetFullScreenCapable
window = frameobj.window()
AttributeError: 'NSHIObject' object has no attribute 'window'
My Code (just copied and pasted into one file from the above link)
# from https://stackoverflow.com/questions/12328143/getting-pyobjc-object-from-integer-id
import ctypes, objc
_objc = ctypes.PyDLL(objc._objc.__file__)
# PyObject *PyObjCObject_New(id objc_object, int flags, int retain)
_objc.PyObjCObject_New.restype = ctypes.py_object
_objc.PyObjCObject_New.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
def objc_object(id):
return _objc.PyObjCObject_New(id, 0, 1)
def SetFullScreenCapable(frame):
frameobj = objc_object(frame.GetHandle())
NSWindowCollectionBehaviorFullScreenPrimary = 1<<7
window = frameobj.window()
newBehavior = window.collectionBehavior() | NSWindowCollectionBehaviorFullScreenPrimary
window.setCollectionBehavior_(newBehavior)
import wxversion
wxversion.select('2-osx_cocoa') # require Cocoa version of wxWidgets
import wx
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.Bind(wx.EVT_CLOSE, self.OnClose)
wx.Button(self, label="Hello!") # test button to demonstrate full-screen resizing
SetFullScreenCapable(self)
def OnClose(self, event):
print "Closing"
exit()
if __name__ == "__main__":
app = wx.App(False)
frame = Frame()
frame.Show()
app.MainLoop()
print "running app loop"
While this is rather late, recently looking at this it suddenly clicked.
If you notice in the error it states a class NSHIObject (HI I am guessing stands for Human Interface) this has to do with the backend that wxPython uses, the archaic Carbon (as in this case) or the updated Cocoa. In earlier versions only Carbon was available but with 2.9.5 (IIRC) Cocoa is available (and I believe it has sense moved to 3.0 with Cocoa or Carbon ). Simply reinstall with a cocoa version and it works.
I'm trying to run an example from the book "Rapid GUI Programming with Python and QT" and I'm getting an error message.
import sys
from math import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Form(QDialog):
def __init__(self,parent = None):
super(Form,self).__init__(parent)
self.browser = QTextBrowser()
self.lineedit = QLineEdit("Type an Expression and press enter")
self.lineedit.selectAll()
layout = QBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
self.connect(self.lineedit, SIGNAL("returnPressed()"),self.UpdateGUI)
self.setWindowTitle("Ryans App")
def UpdateGUI(self):
try
text = self.lineedit.text()
self.browser.append("%s = <b>%s</b>" % (text,eval(text)))
except:
self.browser.append("<font color=red>%s is Invalid!</font>" % text )
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
The trace I'm getting is:
Traceback (most recent call last):
File "C:\Users\MyName\workspaces\LearningProject\src\LearningModule.py", line 33, in <module>
form = Form()
File "C:\Users\MyName\workspaces\LearningProject\src\LearningModule.py", line 16, in __init__
layout = QBoxLayout()
TypeError: QBoxLayout(QBoxLayout.Direction, QWidget parent=None): not enough arguments
I'm confused as to why it's requiring an argument to create the Form object as I'm just trying to inherit from QDialog... am I missing a subtlety in the syntax?
The version I have uses QVBoxLayout instead:
...
self.lineedit.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.browser)
...
My understanding is that since it lines the widgets up vertically, the .LeftToRight and parent are not strictly necessary.
I'm using the most recent code archive for python 2.6 from the book website.
When creating a QBoxLayout, you need to specify a direction (e.g. QBoxLayout.LeftToRight) and optionally a parent (in this case, self should work as the parent).
These should be added on your layout = QBoxLayout() line.
I've made a gui in glade that I want to put in a python program. I was adapting the instructions from a tutorial I found online to load in my glade file (http://www.pygtk.org/articles/pygtk-glade-gui/Creating_a_GUI_using_PyGTK_and_Glade.htm). When I had problems I tried something basic (one button) calling it the same thing as in that tutorial, and copy pasting their code, and it still didn't work. I also took a look at (http://www.linuxjournal.com/article/6586?page=0,2), which has a function being called slightly differently ("self.wTree=gtk.glade.XML (gladefile,windowname)" instead of without windowname), and implemented an equivalent with mine and that didn't fix it. I definitely have pygtk working, I made something without using glade before and it worked fine. The error I'm getting is:
/usr/share/themes/NOX/gtk-2.0/gtkrc:233: Murrine configuration option "gradients"
is no longer supported and will be ignored.
(helloWorld.py:9804): libglade-WARNING **: Expected <glade-interface>. Got
<interface>.
(helloWorld.py:9804): libglade-WARNING **: did not finish in PARSER_FINISH state
Traceback (most recent call last):
File "helloWorld.py", line 31, in <module>
hwg = HellowWorldGTK()
File "helloWorld.py", line 22, in __init__
self.wTree = gtk.glade.XML(self.gladefile)
RuntimeError: could not create GladeXML object
I'm running xubuntu 11.04. The Murrine configuration thing comes up when any gtk application opens, but I included it in case it is relevant. Here's the code I took from the tutorial (but isn't working)
#!/usr/bin/env python
import sys
try:
import pygtk
pygtk.require("2.0")
except:
pass
try:
import gtk
import gtk.glade
except:
sys.exit(1)
class HellowWorldGTK:
"""This is an Hello World GTK application"""
def __init__(self):
#Set the Glade file
self.gladefile = "PyHelloWorld.glade"
self.wTree = gtk.glade.XML(self.gladefile)
#Get the Main Window, and connect the "destroy" event
self.window = self.wTree.get_widget("MainWindow")
self.window.show()
if (self.window):
self.window.connect("destroy", gtk.main_quit)
if __name__ == "__main__":
hwg = HellowWorldGTK()
gtk.main()
Try with this code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
class HellowWorldGTK:
def __init__(self):
self.gladefile = "helloworld.glade"
self.glade = gtk.Builder()
self.glade.add_from_file(self.gladefile)
self.glade.connect_signals(self)
self.glade.get_object("MainWindow").show_all()
def on_MainWindow_delete_event(self, widget, event):
gtk.main_quit()
if __name__ == "__main__":
try:
a = HellowWorldGTK()
gtk.main()
except KeyboardInterrupt:
pass
Remember:
In Glade, Edit the "Preferences" of the file to "GTKBuilder" (not "libglade")
Your PyHelloWorld.glade is incorrect. Make sure you created it with the correct Glade application, there are Glade2 and Glade3 applications that can be installed and used. If you downloaded the file make sure it is correct. The error message says it all:
Expected <glade-interface>. Got <interface>
So the XML file has the interface tag, but PyGTK library expects glade-interface tag.
Since I always end up having problems with this, here is a Python 2.7 code that I use for one or the other:
for Libglade:
# needs libglade (not for gtk-builder)
import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
gladefile = "test-libglade.glade"
wTree = gtk.glade.XML(gladefile)
window = wTree.get_widget("MainWindow")
if (window):
window.connect("destroy", gtk.main_quit)
window.show_all() # must have!
gtk.main()
For GtkBuilder:
# needs gtk-builder (not for libglade)
import pygtk
pygtk.require("2.0")
import gtk
gladefile = "test-gtkbuilder.glade"
wTree = gtk.Builder()
wTree.add_from_file(gladefile)
window = wTree.get_object("MainWindow")
if (window):
window.connect("destroy", gtk.main_quit)
window.show_all() # must have!
gtk.main()
In Glade, you can just add a Window, call it MainWindow, and save two versions with the respective filenames as above for each format; and these snippets should work with them respeactively.
Hope this helps someone,
Cheers!
This works perfectly.
#!/usr/bin/python
import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
class SubinsWindow:
def __init__(self):
self.gladefile = "game.glade"
self.glade = gtk.Builder()
self.glade.add_from_file(self.gladefile)
self.glade.connect_signals(self)
self.win=self.glade.get_object("window1") # Window Name in GLADE
self.win.show_all()
if __name__ == "__main__":
a = SubinsWindow()
gtk.main()
If you are using GTK+3 in python, see builder.
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class Handler:
def onDestroy(self, *args):
Gtk.main_quit()
def onButtonPressed(self, button):
print("Hello World!")
builder = Gtk.Builder()
builder.add_from_file("builder_example.glade")
builder.connect_signals(Handler())
window = builder.get_object("window1")
window.show_all()
Gtk.main()