Label mit Bild füllen

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, folgender Code

Code: Alles auswählen

# -*- coding: utf-8 -*-
"""
Created on Thu Mar 03 13:18:50 2016

@author: rk480158
"""

from Tkinter import *
import numpy as np
from random import randint
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
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


v=""
g=0
dot = 0
#def sende1():                
# # s = Eingabefeld1.get()
#    global s
#    v=Eingabefeld1.get()
#    print "v in sende ist jetzt",v
#    g=int(v)
#    if g>0:
#        if  g == dot:
#            print dot
#            z = Label(root, text="Richtig")
#            z.pack()
#        else: 
#            z = Label(root, text="Falsch")
#            z.pack()

  
# root = Tk()
# Label(root, text="Ergebnis").grid(row=0)
# Label(root, text="Ergebnis").grid(row=1)
# e1 = Entry(root)
# e2 = Entry(root)
# e1.grid(row=0, column=1)
# e2.grid(row=1, column=1) 
# master = Tk()
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
    
    
    
def ausgang():
    headerLabels = '$C_{soil}=(1 - n) C_m + \\theta_w C_w$'
    def sende1():                
 # s = Eingabefeld1.get()
        global s
        v=Eingabefeld1.get()
        print "v in sende ist jetzt",v
        g=int(v)
        if g:
            if  g == dot:
                print dot
                z = Label(root, text="Richtig")
                z.pack()
            else: 
                z = Label(root, text="Falsch")
                z.pack()     
    
    root=Tk()
    s = StringVar()
    c = Label(root, text=mathTex_to_QPixmap(headerLabels, 10))
    c.pack()
# v = StringVar()
    Eingabefeld1= Entry(root,bg='white', textvariable=s)
    Eingabefeld1.pack()
# w = Label(root, text="Hello Tkinter!")
# w.pack()
    x1 = randint(-10,10)
    x2 = randint(-10,10)
    x3 = randint(-10,10)
    x= np.array([x1,x2,x3])
##x_shape = np.array([0,0,0])
##for i in xrange(len(x)):
##    x_shape[i]=x[i]
##
##x_shape.shape = (3,1)
    a = Label(root, text=x)
    a.pack()
    y1 = randint(-10,10)
    y2 = randint(-10,10)
    y3 = randint(-10,10)
    y = np.array([y1,y2,y3])

#    x = Matrix([randint(-20,20), randint(-20,20), randint(-20,20)])
#    y = Matrix([randint(-20,20), randint(-20,20), randint(-20,20)])
    a1 = latex(x)
    
#    a2 = latex(y)
#    print "a1 ist jetzt", a1
    a1 = a1.replace("left[", "left(")
#    a2 = a2.replace("left[", "left(")
    a1 = a1.replace("right]", "right)")
#    a2 = a2.replace("right]", "right)")
#    str1 = "$\langle" + a1 + ", " + a2 + "\\rangle$"

    # y_transpose = np.transpose(y)
    print a1
    b = Label(root, text=y)
    b.pack() 
    dot = np.dot(x,y)
    #dot = x.dot(y)
    #print dot
    Knopf1 = Button(root,text='Sende Ergebnis',command=sende1)
    Knopf1.pack(side=LEFT)
    Knopf2 = Button(root,text='Neue Berechnung',command=ausgang)
    Knopf2.pack(side=RIGHT)
    root.mainloop()
# print s
# v=s.get()
# print "v ist jetzt:",v
# s=Eingabefeld1.get()
# z = Label(root, text=dot)
# z.pack()
# try:
#    v
# except NameError:
#    v = "None"

# print "v ist jetzt nach None:",v

# if v!="":
#    g = int(v)
#    print "v jetzt im Vergleich ist", v
# print "g ist:",g
#if g>0:
#    if  g == dot:
#        print dot
#        z = Label(root, text="Richtig")
#        z.pack()
#    else: 
#        z = Label(root, text="Falsch")
#        z.pack()

# root = Tk()

ausgang()

# root.mainloop()
# mainloop()
Ich würde gerne das Bild, welches ich aus def mathTex_to_QPixmap(mathTex, fs): generiere in einem Label darstellen; hier der label c. Wie geht das? Der vorliegende Code führt nur dazu dass ich den kernel reloaden muss, ist also fehlerhaft.
BlackJack

@Brando: Also ich bekomme da die Meldung

Code: Alles auswählen

QPixmap: Must construct a QApplication before a QPaintDevice
Aborted (core dumped)
ausgegeben.

Das ist an sich ja schon mal ein Hinweis was falsch gemacht wird, allerdings wird das erstellen eines `QApplication`-Exemplars nur ein Stückchen weiterhelfen weil Tk mit `QPixmap`-Objekten nichts anfangen kann. Das möchte `Tkinter.PhotoImage`-Exemplare oder etwas kompatibles, und das dann auch nicht als `text`-Argument, denn Bilder sind kein Text. ;-)

Du solltest Dich für *ein* GUI-Rahmenwerk (pro Programm) entscheiden. Die zu mischen ist keine gute Idee und es ist auch nicht garantiert, dass das funktioniert.

Ich hatte im anderen Thema ja schon mal die Dokumentation der `latex()`-Funktion als Lektüre empfohlen — diese `replace()`-Operationen auf dem Ergebnis kann man sich sparen wenn man die Funktion mit den passenden Argumenten aufruft.
Brando
User
Beiträge: 171
Registriert: Donnerstag 28. Januar 2016, 15:36

Jetzt habe ich alles auf PyQT umgestellt, also benutze ich tkinter nicht mehr. Aber mein Code funktioniert 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
from PyQt4 import QtGui



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
    
def window():
   app = QtGui.QApplication(sys.argv)
   w = QtGui.QWidget()
   b = QtGui.QLabel(w)
   headerline= '$C_{soil}=(1 - n) C_m + \\theta_w C_w$'
   bild = mathTex_to_QPixmap(headerline, 15)
   # print(bild)
   b.picture(bild)
   w.setGeometry(100,100,200,50)
   b.move(50,20)
   w.setWindowTitle("PyQt")
   w.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   window()
BlackJack

@Brando: Was ist denn an der Fehlermeldung unverständlich?

Code: Alles auswählen

Traceback (most recent call last):
  File "forum.py", line 98, in <module>
    window()
  File "forum.py", line 88, in window
    bild = mathTex_to_QPixmap(headerline, 15)
  File "forum.py", line 49, in mathTex_to_QPixmap
    fig = mpl.figure.Figure()
NameError: global name 'mpl' is not defined
Brando
User
Beiträge: 171
Registriert: Donnerstag 28. Januar 2016, 15:36

Mittlerweile habe ich meinen Code verbessert, und er zeigt die Vektoren richtig an. Ein Problem bleibt aber: Wie kann ich ein Clickereignis eines Buttons simulieren? Das funktioniert bei meinem Code noch nicht. Eine Idee, woran das liegen könnte?

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()
Antworten