I am working on an multiform application where I am able to link the (form1 to form2 and form3), (form2 to form3) but when I am trying to create a link from (form2 to form1) and from3 to (form2 or form1) link to the backward page it is giving me the error NameError: global name is not defined.
Here is my calling methods code where form3 can call form4 but form4 does not call form3;
Code : form3.py
class Ui_DiabeticRetinopathy3(QtGui.QMainWindow):
def __init__(self,parent=None):
super(Ui_DiabeticRetinopathy3, self).__init__(parent)
self.imgPreProc = imagePreProcessor()
#self.imgPreProc = imagePreProcessor()
self.setupUi(self)
def setupUi(self, DiabeticRetinopathy):
DiabeticRetinopathy.setObjectName(_fromUtf8("DiabeticRetinopathy"))
DiabeticRetinopathy.resize(672, 608)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("../im0003.jpg")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
DiabeticRetinopathy.setWindowIcon(icon)
self.pushButton_6 = QtGui.QPushButton(self.verticalLayoutWidget_2)
self.pushButton_6.setStyleSheet(_fromUtf8("background-color: rgb(191, 191, 191);\n"
"font: 75 8pt \"Verdana\";"))
self.pushButton_6.setObjectName(_fromUtf8("pushButton_6"))
self.verticalLayout_2.addWidget(self.pushButton_6)
self.pushButton_6.clicked.connect(self.on_clicked_hemo)
def on_clicked_hemo(self):
self.obj4=Ui_DiabeticRetinopathy4(self)
self.obj4.show()
Code : form4.py
class Ui_DiabeticRetinopathy4(QtGui.QMainWindow):
def __init__(self,parent=None):
super(Ui_DiabeticRetinopathy4, self).__init__(parent)
self.imgPreProc = imagePreProcessor()
#self.obj3=Ui_DiabeticRetinopathy3()
#self.imgPreProc = imagePreProcessor()
self.setupUi(self)
def setupUi(self, DiabeticRetinopathy):
DiabeticRetinopathy.setObjectName(_fromUtf8("DiabeticRetinopathy"))
DiabeticRetinopathy.resize(672, 608)
DiabeticRetinopathy.setWindowIcon(icon)
self.pushButton_6 = QtGui.QPushButton(self.verticalLayoutWidget)
self.pushButton_6.setObjectName(_fromUtf8("pushButton_6"))
self.verticalLayout_2.addWidget(self.pushButton_6)
#self.pushButton_6.clicked.connect(self.on_clicked_micro)#####
def on_clicked_micro(self):
self.obj3=Ui_DiabeticRetinopathy3(self)
#self.obj3.setupUi(self)
self.obj3.show()
Any help will be greatly appreciated!
NameError: name 'Ui_DiabeticRetinopathy3' is not defined
If it possibility, please check your import module. Have you import form3.py into form4.py?
In form4.py, It should be possibility like this in head;
from form3 import *
from form3 import Ui_DiabeticRetinopathy3
Related
I have tried to boil down my program to be as simple as possible and still be functional. First is my UI file with the tabs that I want. It has a graph in the Control tab and I want the play button to start the plot.
When I start it I can't get the graph to show up. any help would be appreciated.
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.tabWidget = QtGui.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 421))
self.tabWidget.setStyleSheet(_fromUtf8(""))
self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
self.tab_4 = QtGui.QWidget()
self.tab_4.setObjectName(_fromUtf8("tab_4"))
self.tabWidget.addTab(self.tab_4, _fromUtf8(""))
self.tab_2 = QtGui.QWidget()
self.tab_2.setObjectName(_fromUtf8("tab_2"))
self.tabWidget.addTab(self.tab_2, _fromUtf8(""))
self.tab = QtGui.QWidget()
self.tab.setObjectName(_fromUtf8("tab"))
self.pushButton = QtGui.QPushButton(self.tab)
self.pushButton.setGeometry(QtCore.QRect(290, 340, 75, 31))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("play_button.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton.setIcon(icon)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton_2 = QtGui.QPushButton(self.tab)
self.pushButton_2.setGeometry(QtCore.QRect(460, 340, 75, 31))
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("pause_button.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_2.setIcon(icon1)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.pushButton_3 = QtGui.QPushButton(self.tab)
self.pushButton_3.setGeometry(QtCore.QRect(630, 340, 75, 31))
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(_fromUtf8("resume_button.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_3.setIcon(icon2)
self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
self.graphicsView = QtGui.QGraphicsView(self.tab)
self.graphicsView.setGeometry(QtCore.QRect(205, 1, 591, 341))
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.tabWidget.addTab(self.tab, _fromUtf8(""))
self.tab_3 = QtGui.QWidget()
self.tab_3.setObjectName(_fromUtf8("tab_3"))
self.tabWidget.addTab(self.tab_3, _fromUtf8(""))
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(2)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("MainWindow", "Calibration", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Material", None))
self.pushButton.setText(_translate("MainWindow", "Start Plot", None))
self.pushButton_2.setText(_translate("MainWindow", "Pause", None))
self.pushButton_3.setText(_translate("MainWindow", "Resume", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Control", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Operator", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
The second is my graphing class which does work when I make a gui with code, but I would like to be able to plug it into a program with a ui file.
import sys
import time
import datetime
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import pyqtgraph as pg
import random
from workingraspitab2 import Ui_MainWindow
class Main(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.setupUi(self)
self.graphicsView = QtGui.QStackedWidget()
self.login_widget = LoginWidget(self)
self.graphicsView.addWidget(self.login_widget)
self.pushButton.clicked.connect(self.plotter)#the play button
self.curve = self.login_widget.it1
self.curve2 =self.login_widget.it2
def plotter(self):
self.data =[0]
self.data2 = [0]
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.updater)
self.timer.start(0)
print self.data
def updater(self):
self.data.append(self.data[-1]+10*(0.5-random.random()))
self.curve.setData(self.data, pen=pg.mkPen('b', width=1))
self.data2.append(self.data2[-1]+0.1*(0.5-random.random()))
self.curve2.setData(self.data2, pen=pg.mkPen('r', width=1))
print self.data
class LoginWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(LoginWidget, self).__init__(parent)
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
self.plot = pg.PlotWidget(title='Force and Extension vs. Time')
p1 = self.plot.plotItem
p2 = pg.ViewBox()
p1.showAxis('right')
p1.scene().addItem(p2)
p1.getAxis('right').linkToView(p2)
p2.setXLink(p1)
self.plot.getAxis('bottom').setLabel('Time', units='s')
self.plot.getAxis('left').setLabel('Force', units='lbf', color="#0000ff")
p1.getAxis('right').setLabel('Extension', units='in.', color="#ff0000")
def updateViews():
p2.setGeometry(p1.vb.sceneBoundingRect())
p2.linkedViewChanged(p1.vb, p2.XAxis)
updateViews()
p1.vb.sigResized.connect(updateViews)
self.it1 = p1.plot()
self.it2 = pg.PlotCurveItem()
p2.addItem(self.it2)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Main()
window.show()
sys.exit(app.exec_())
Had to put everything in the Main class to get it to work. I was hoping for a more elegant solution. I still cant get the background or foreground to change, but it is working and here is the code:
class Main(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.setupUi(self)
pv = self.graphicsView
pv.setTitle('Force and Extension vs. Time')
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
p1 = pv.plotItem
p2 = pg.ViewBox()
p1.showAxis('right')
p1.scene().addItem(p2)
p1.getAxis('right').linkToView(p2)
p2.setXLink(p1)
pv.getAxis('bottom').setLabel('Time', units='s')
pv.getAxis('left').setLabel('Force', units='lbf', color="#0000ff")
p1.getAxis('right').setLabel('Extension', units='in.', color="#ff0000")
def updateViews():
p2.setGeometry(p1.vb.sceneBoundingRect())
p2.linkedViewChanged(p1.vb, p2.XAxis)
updateViews()
p1.vb.sigResized.connect(updateViews)
self.it1 = p1.plot()
self.it2 = pg.PlotCurveItem()
p2.addItem(self.it2)
self.pushButton.clicked.connect(self.plotter)
self.pushButton_2.clicked.connect(lambda: self.timer.stop())
self.pushButton_3.clicked.connect(self.timer_start)
self.curve = self.it1
self.curve2 = self.it2
I have an issue with my code. I'm fairly new to python and I'm trying new things. I want to create a geography quiz that will randomly ("but not repeatedly") select country that I have to guess its capital. Currently for every answer I get a message that my answer is wrong. The question is how exactly should I do things so that when I loop through the dictionary for a country, I will have to guess the correct key of that country.
Here is the code:
#!/usr/bin/env python
import os
import jinja2
import webapp2
import random
template_dir = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)
class BaseHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
return self.response.out.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
return self.write(self.render_str(template, **kw))
def render_template(self, view_filename, params=None):
if not params:
params = {}
template = jinja_env.get_template(view_filename)
return self.response.out.write(template.render(params))
class MainHandler(BaseHandler):
def get(self):
return self.render_template("geokviz.html")
class AboutHandler(BaseHandler):
def get(self):
return self.render_template("geokviz1.html")
class flagHandler(BaseHandler):
def get(self):
return self.render_template("flag.html")
class attractionHandler(BaseHandler):
def get(self):
return self.render_template("attraction.html")
class Capital:
def __init__(self, capital, country):
self.capital = capital
self.country = country
city = {"Zagreb":"Croatia", "Ljubljana":"Slovenia", "Rome":"Italy", "Oslo":"Norway"}
class capitalCityHandler(BaseHandler):
def get(self):
for cities in random.sample(list(city), 1):
capital = city[cities]
params={"capital": capital}
return self.render_template("capital.html", params=params)
def post(self):
odgovor = self.request.get("answer")
if odgovor == city.keys():
result1 = "You are right"
else:
result1 = "You are wrong"
self.write(result1)
app = webapp2.WSGIApplication([
webapp2.Route('/', MainHandler),
webapp2.Route('/geo', AboutHandler),
webapp2.Route('/city', capitalCityHandler),
webapp2.Route('/flag', flagHandler),
webapp2.Route('/attraction', attractionHandler),
], debug=True)
Thanks for all the help
First, you need to check if the capital exists as a key, then you may check if it matches the country.
if odgovor in city.keys() and city[odgovor] == country:
I want to set value into sheet using thread.
import time
import wx
from wx.lib import sheet
from threading import Thread
EVT_RESULT_ID = wx.NewId()
def EVT_RESULT(win, func):
win.Connect(-1, -1, EVT_RESULT_ID, func)
class ResultEvent(wx.PyEvent):
def __init__(self, data):
wx.PyEvent.__init__(self)
self.SetEventType(EVT_RESULT_ID)
self.data = data
class TestThread(Thread):
def __init__(self, wxObject,sheet):
Thread.__init__(self)
self.wxObject = wxObject
self.sheet=sheet
self.start()
def run(self):
self.sheet.sheetload()
wx.PostEvent(self.wxObject, ResultEvent(self.sheet))
class MySheet(sheet.CSheet):
def __init__(self, parent):
sheet.CSheet.__init__(self, parent)
self.SetNumberRows(100)
self.SetNumberCols(30)
def sheetload(self):
self.SetNumberRows(200)
self.SetNumberCols(30)
self.EnableEditing(False)
for i in range(200):
for j in range(30):
self.SetCellValue(i,j,str(i))
class Newt(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None,-1, "Tutorial")
self.box = wx.BoxSizer(wx.VERTICAL)
toolbar2 = wx.ToolBar(self, wx.TB_HORIZONTAL | wx.TB_TEXT,size = (1000, 40))
self.show_btn =wx.Button(toolbar2, label="show")
self.show_btn.Enable(True)
self.Bind(wx.EVT_BUTTON, self.onShow,self.show_btn)
toolbar2.AddControl(self.show_btn)
self.box.Add((5,5) , 0)
self.box.Add(toolbar2)
self.box.Add((5,10) , 0)
toolbar2.Realize()
self.notebook = wx.Notebook(self, -1, style=wx.RIGHT)
self.box.Add(self.notebook, 1, wx.EXPAND)
self.Maximize(True)
self.SetSizer(self.box)
EVT_RESULT(self, self.updateDisplay)
def onShow(self, event):
sheet=MySheet(self.notebook)
TestThread(self,sheet)
def updateDisplay(self, msg):
t = msg.data
self.notebook.AddPage(t,"Logs")
app = wx.PySimpleApp()
frame = Newt().Show()
app.MainLoop()
Here I am using sheetload function defined in Mysheet to execute in TestThread. So i can set value into sheet in background without blocking main gui.
But i am getting this error, and my gui is crashing.
(python2.7:10775): GLib-CRITICAL **: Source ID 559 was not found when attempting to remove it
can you help me, what is wrong with this code.
I am having an error against an innocent wish to play an audio in audio player using Tkinter. Error is:
Traceback (most recent call last):
File "C:\Users\Mudassar\workspace\Player\main_gui.py", line 43, in
<module>
app = GUI(playerobj)
File "C:\Users\Mudassar\workspace\Player\main_gui.py", line 10, in
__init__
self.create_button_frame()
AttributeError: GUI instance has no attribute 'create_button_frame'
My Code main_gui.py is:
from Tkinter import *
import tkFileDialog
import player
class GUI:
def __init__(self, player):
self.player = player
player.parent = player
self.root = Tk()
self.create_button_frame()
self.create_bottom_frame()
self.root.mainloop()
def create_button_frame(self):
buttonframe = Frame(self.root)
self.playicon = PhotoImage(file='../icons/play.gif')
self.stopicon = PhotoImage(file='../icons/stop.gif')
self.playbtn=Button(buttonframe, text ='play', image=self.playicon,
borderwidth=0, command=self.toggle_play_pause)
self.playbtn.image = self.playicon
self.playbtn.grid(row=3, column=3)
buttonframe.grid(row=1, pady=4, padx=5)
def create_bottom_frame(self):
bottomframe = Frame(self.root)
add_fileicon = PhotoImage(file='../icons/add_file.gif')
add_filebtn = Button(bottomframe, image=add_fileicon, borderwidth=0,
text='Add File', command = self.add_file)
add_filebtn.image = add_fileicon
add_filebtn.grid(row=2, column=1)
bottomframe.grid(row=2, sticky='w', padx=5)
def toggle_play_pause(self):
if self.playbtn['text'] == 'play':
self.playbtn.config(text='stop', image=self.stopicon)
self.player.start_play_thread()
elif self.playbtn['text'] == 'stop':
self.playbtn.config(text = 'play', image=self.playicon)
self.player.pause()
def add_file(self):
tfile = tkFileDialog.askopenfilename(filetypes = [('All supported',
'.mp3 .wav .ogg'), ('All files', '*.*')])
self.currentTrack = tfile
if __name__=='__main__':
playerobj = player.Player()
app = GUI(playerobj)
My Player button functions in another (as they have nothing to do with error)are:
import pyglet
from threading import Thread
class Player():
parent = None
def play_media(self):
try:
self.myplayer=pyglet.media.Player()
self.source = pyglet.media.load(self.parent.currentTrack)
self.myplayer.queue(self.source)
self.myplayer.queue(self.source)
self.myplayer.play()
pyglet.app.run()
except:
pass
def start_play_thread(self):
player_thread = Thread(target=self.play_media)
player_thread.start()
def pause(self):
try:
self.myplayer.pause()
self.paused = True
except: pass
Please help.
Seems like your problem is indentation. Your create_button_frame() function is not an attribute of the class GUI, it is a global function. Indent all the functions taking parameter self four spaces to the right. Then they will be methods of your class GUI.
I have created a setting window in python where i have a few path settings which has to be one time setting.Here is the sample demo code,
import wx
import os
class SettingWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title)
panel= wx.Panel(self,-1)
font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD)
field1 = wx.TextCtrl(panel,pos=(120,25),size=(170,20))
vsizer = wx.BoxSizer(wx.VERTICAL)
field1_sz=wx.BoxSizer(wx.HORIZONTAL)
field2_sz=wx.BoxSizer(wx.HORIZONTAL)
field1_lbl=wx.StaticText(panel,-1, label='Repo URL path:', pos=(25, 25))
field1_lbl.SetFont(font)
field1_sz.AddSpacer(50)
field1_sz.Add(field1_lbl)
field1_sz.AddSpacer(5) # put 5px of space between
field1_sz.Add(field1)
field1_sz.AddSpacer(50)
vsizer.AddSpacer(50)
vsizer.Add(field1_sz)
vsizer.AddSpacer(15)
vsizer.Add(field2_sz)
vsizer.AddSpacer(50)
btn1 = wx.Button(panel, label='Browse',pos=(300,25),size=(60,20))
btn1.Bind(wx.EVT_BUTTON, self.opendir)
def opendir(self, event):
dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dlg.ShowModal() == wx.ID_OK:
field1.SetValue("%s",dlg.GetPath())
dlg.Destroy()
class MyApp(wx.App):
def OnInit(self):
frame= SettingWindow(None,-1,'Setting Window')
frame.Show()
self.SetTopWindow(frame)
return True
app= MyApp(0)
app.MainLoop()
I want to display the path which i get from opendir in textCtrl.I am finding an error like below,
Traceback (most recent call last):
File "D:\PROJECT\SettingWindow.py", line 58, in opendir
return (field1)
NameError: global name 'field1' is not defined
use self.field1 instead of variable field1:
self.field1 = wx.TextCtrl(panel,pos=(120,25),size=(170,20))
self.field1.SetValue(dlg.GetPath())
This code works to make the TextCtrl field hidden when clicked on the checkbox
def OnCheckBox(self,event):
if self.checkbox.Value==False:
self.field.Enable(True)
else:
self.field.Enable(False)