Wie kann ich eine Messagebox auslösen?

Python und das Qt-Toolkit, erstellen von GUIs mittels des Qt-Designers.
Antworten
Brando
User
Beiträge: 171
Registriert: Donnerstag 28. Januar 2016, 15:36

Hallo hier habe ich einen Code, der mir zwei Vektoren anzeigt, und darüber hinaus soll es funktionieren, dass ich beim Drücken des Knopfes Berechnen eine MessageBox angezeigt bekomme. Das funktioniert aber noch nicht. Was mache ich falsch?

Code: Alles auswählen

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 21 10:43:11 2016

@author: rk480158
"""


import sys
import matplotlib as mpl
from matplotlib.backends.backend_agg import FigureCanvasAgg
from PyQt4  import QtGui, QtCore
import matplotlib.pyplot as plt
from matplotlib import rcParams
from sympy.matrices import *
from sympy.printing import *
from IPython.display import display, HTML, Math, Latex, clear_output
# from ipywidgets import widgets
from random import randint


def mathTex_to_QPixmap(mathTex, fs):

    #---- set up a mpl figure instance ----

    fig = mpl.figure.Figure()
    fig.patch.set_facecolor('none')
    fig.set_canvas(FigureCanvasAgg(fig))
    renderer = fig.canvas.get_renderer()

    #---- plot the mathTex expression ----

    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')
    ax.patch.set_facecolor('none')
    t = ax.text(0, 0, mathTex, ha='left', va='bottom', fontsize=fs)

    #---- fit figure size to text artist ----

    fwidth, fheight = fig.get_size_inches()
    fig_bbox = fig.get_window_extent(renderer)

    text_bbox = t.get_window_extent(renderer)

    tight_fwidth = text_bbox.width * fwidth / fig_bbox.width
    tight_fheight = text_bbox.height * fheight / fig_bbox.height

    fig.set_size_inches(tight_fwidth, tight_fheight)

    #---- convert mpl figure to QPixmap ----

    buf, size = fig.canvas.print_to_buffer()
    qimage = QtGui.QImage.rgbSwapped(QtGui.QImage(buf, size[0], size[1],
                                                  QtGui.QImage.Format_ARGB32))
    qpixmap = QtGui.QPixmap(qimage)

    # return qpixmap.toImage()
    # return qimage
    return qpixmap
    
def window():
   app = QtGui.QApplication(sys.argv)
   rcParams['text.usetex'] = True
   rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
   x = Matrix()
   x = Matrix([randint(-20,20), randint(-20,20), randint(-20,20)])
   a1 = latex(x) 
   w = QtGui.QWidget()
   b = QtGui.QLabel(w)
   headerline='$%s$'%a1
  # headerline= '$C_{soil}=(1 - n) C_m + \\theta_w C_w$'
   bild = mathTex_to_QPixmap(headerline, 15)
   label_x = QtGui.QLabel(w)
   # pixmap = QPixmap(sys.argv[1])
   label_x.setPixmap(bild)
   label_x.setGeometry(5,5,50,100)
   label_x.show()
   
   y = Matrix()
   y = Matrix([randint(-20,20), randint(-20,20), randint(-20,20)])
   a2 = latex(y) 
   headerline='$%s$'%a2
  # headerline= '$C_{soil}=(1 - n) C_m + \\theta_w C_w$'
   bild = mathTex_to_QPixmap(headerline, 15)
   label_y = QtGui.QLabel(w)
   # pixmap = QPixmap(sys.argv[1])
   label_y.setPixmap(bild)
   label_y.setGeometry(50,5,50,100)
   label_y.show()
   
   label_aufgabe = QtGui.QLabel(w)
   label_aufgabe.setText("Wie lautet das Skalarprodukt?")
   label_aufgabe.show()
   
   nm=QtGui.QLineEdit(w)
   nm.setGeometry(5,100,40,40)
   nm.show()
   zahl =  nm.text()
   b1=QtGui.QPushButton(w)
   b1.setGeometry(5,170,70,40)
   b1.setText("Berechnen")
   b1.show()
   b1.clicked.connect(showdialog)   # print ("%s"%zahl)
   # print(bild)
   #b.picture(bild)
   w.setGeometry(100,100,200,200)
  # b.move(50,20)
   w.setWindowTitle("PyQt")
   w.show()
   sys.exit(app.exec_())

def showdialog():
   msg = QtGui.QMessageBox()
   msg.setIcon(QMessageBox.Information)

   msg.setText("This is a message box")
   msg.setInformativeText("This is additional information")
   msg.setWindowTitle("MessageBox demo")
   msg.setDetailedText("The details are as follows:")
   msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
   msg.show()
   #msg.buttonClicked.connect(msgbtn)
	
   #retval = msg.exec_()
	
if __name__ == '__main__':
   window()
BlackJack

@Brando: Und wieder die Rückfrage was an der Fehlermeldung

Code: Alles auswählen

Traceback (most recent call last):
  File "forum.py", line 146, in showdialog
    msg.setIcon(QMessageBox.Information)
NameError: global name 'QMessageBox' is not defined
unverständlich ist‽
Brando
User
Beiträge: 171
Registriert: Donnerstag 28. Januar 2016, 15:36

Mein neuester Code; allerdings reagiert der Button immer noch nicht und sendet keine Messagebox

Code: Alles auswählen

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 21 10:43:11 2016

@author: rk480158
"""


import sys
import matplotlib as mpl
from matplotlib.backends.backend_agg import FigureCanvasAgg
from PyQt4  import QtGui, QtCore
from PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT
import matplotlib.pyplot as plt
from matplotlib import rcParams
from sympy.matrices import *
from sympy.printing import *
from IPython.display import display, HTML, Math, Latex, clear_output
# from ipywidgets import widgets
from random import randint


def mathTex_to_QPixmap(mathTex, fs):

    #---- set up a mpl figure instance ----

    fig = mpl.figure.Figure()
    fig.patch.set_facecolor('none')
    fig.set_canvas(FigureCanvasAgg(fig))
    renderer = fig.canvas.get_renderer()

    #---- plot the mathTex expression ----

    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')
    ax.patch.set_facecolor('none')
    t = ax.text(0, 0, mathTex, ha='left', va='bottom', fontsize=fs)

    #---- fit figure size to text artist ----

    fwidth, fheight = fig.get_size_inches()
    fig_bbox = fig.get_window_extent(renderer)

    text_bbox = t.get_window_extent(renderer)

    tight_fwidth = text_bbox.width * fwidth / fig_bbox.width
    tight_fheight = text_bbox.height * fheight / fig_bbox.height

    fig.set_size_inches(tight_fwidth, tight_fheight)

    #---- convert mpl figure to QPixmap ----

    buf, size = fig.canvas.print_to_buffer()
    qimage = QtGui.QImage.rgbSwapped(QtGui.QImage(buf, size[0], size[1],
                                                  QtGui.QImage.Format_ARGB32))
    qpixmap = QtGui.QPixmap(qimage)

    # return qpixmap.toImage()
    # return qimage
    return qpixmap
    
def window():
   app = QtGui.QApplication(sys.argv)
   rcParams['text.usetex'] = True
   rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
   x = Matrix()
   x = Matrix([randint(-20,20), randint(-20,20), randint(-20,20)])
   a1 = latex(x) 
   w = QtGui.QWidget()
   b = QtGui.QLabel(w)
   headerline='$%s$'%a1
  # headerline= '$C_{soil}=(1 - n) C_m + \\theta_w C_w$'
   bild = mathTex_to_QPixmap(headerline, 15)
   label_x = QtGui.QLabel(w)
   # pixmap = QPixmap(sys.argv[1])
   label_x.setPixmap(bild)
   label_x.setGeometry(5,5,50,100)
   label_x.show()
   
   y = Matrix()
   y = Matrix([randint(-20,20), randint(-20,20), randint(-20,20)])
   a2 = latex(y) 
   headerline='$%s$'%a2
  # headerline= '$C_{soil}=(1 - n) C_m + \\theta_w C_w$'
   bild = mathTex_to_QPixmap(headerline, 15)
   label_y = QtGui.QLabel(w)
   # pixmap = QPixmap(sys.argv[1])
   label_y.setPixmap(bild)
   label_y.setGeometry(50,5,50,100)
   label_y.show()
   
   label_aufgabe = QtGui.QLabel(w)
   label_aufgabe.setText("Wie lautet das Skalarprodukt?")
   label_aufgabe.show()
   
   nm=QtGui.QLineEdit(w)
   nm.setGeometry(5,100,40,40)
   nm.show()
   #zahl =  nm.text()
   b1=QtGui.QPushButton(w)
   b1.setGeometry(5,170,70,40)
   b1.setText("Berechnen")
   b1.show()
   b1.connect(b1,SIGNAL("clicked()"),b1,SLOT("showdialog()"))
  # if (b1.clicked.connect(self.buttonClicked)):
   #   showdialog()
   w.setGeometry(100,100,200,200)
# b.move(50,20)
   w.setWindowTitle("PyQt")
   w.show()
   sys.exit(app.exec_())

def showdialog():
   msg = QtGui.QMessageBox()
   msg.setIcon(QtGui.QMessageBox.Information)

   msg.setText("This is a message box")
   msg.setInformativeText("This is additional information")
   msg.setWindowTitle("MessageBox demo")
   msg.setDetailedText("The details are as follows:")
   msg.setStandardButtons(QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
   msg.exec_()
   #msg.buttonClicked.connect(msgbtn)
	
   #retval = msg.exec_()
	
if __name__ == '__main__':
   window()
BlackJack

@Brando: Du musst wirklich mal lernen die Ausgaben zu lesen:

Code: Alles auswählen

Object::connect: No such slot QPushButton::showdialog()
Die `QObject.connect()`-Methode ist in der Hinsicht auch etwas ungünstig weil das nur zu so einer Warnausgabe führt. Die `connect()`-Methode auf Signalen löst in solchen Fällen eine Ausnahme aus. Ist ausserdem kürzer zu schreiben.
Antworten