Wie kann ich Textboxes zu einer List/Array hinzufügen

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
Brando
User
Beiträge: 171
Registriert: Donnerstag 28. Januar 2016, 15:36

Folgender Code:

Code: Alles auswählen

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 numpy as np
from builtins import str
 
text1 = widgets.Text()
text=[] 
button1 = widgets.Button(description="Auswerten")
button2 = widgets.Button(description="Neue Aufgabe")
 
#x = np.arange(9).reshape(3,3)
#y = np.arange(3).reshape(3,1)
x=Matrix()
y=Matrix()
latexWidget = widgets.Latex()
 
taskWidget = widgets.HTML()
taskWidget.value = "<b>Berechnen Sie:</b>"
 
mhbox1 = widgets.HBox((taskWidget, latexWidget))
mhbox2 = widgets.HBox((button1, button2))
cb_container= []


 
def init_vectors(b):
        global x, y, text1, text, cb_container
        cb_container=[]
        cb_container.append(widgets.HBox())
        cb_container.append(widgets.HBox())
        cb_container.append(widgets.HBox())

        for j in range(3):
           for i in range(3):
             text.append(widgets.Text(width=40))
           
           cb_container[j].children=[i for i in text]
           text=[]
        x=zeros(3,3)
        y=zeros(3,1)
        for i in range(3):
            for j in range(3):
             x[j,i]=randint(-10,10)

        for i in range(1):
            for j in range(3):
               y[j,i]=randint(-10,10)
        
        #n_matrix_x=np.eye(3)
        n_matrix_x=np.matrix(x).astype(float)
        
        gefunden=False
        if np.linalg.det(n_matrix_x)==0:
            init_vectors(b)
        else: 
            A,B=np.linalg.eig(n_matrix_x)
            for i in range(3):
               if A[i].real==0 or A[i].imag!=0:
                 gefunden=True
                 break
               
            
            
            n_matrix_x=np.matrix(x).astype(float)
            n_matrix_y=np.matrix(y).astype(float)
            z = np.linalg.solve(n_matrix_x,n_matrix_y)
            for i in range(3):
                if z[i,0]!= int(z[i,0]):
                   gefunden=True
                   break
            
            if gefunden:
                 init_vectors(b)      
                 
        text1.value = ""
        display_task()
 
def display_task():
        global x, y, latexWidget
 
        clear_output()
 
        a1 = latex(x)
        a2 = latex(y)
 
        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$"
        latexWidget.value = str1
 
def evaluate(b):
        global x, y, text1
        n_matrix_x=np.matrix(x).astype(float)
        n_matrix_y=np.matrix(y).astype(float)
        z = np.linalg.solve(n_matrix_x,n_matrix_y)
        w=widgets.Textarea(Description='Lösung GLS',
                 value=str(z)
                 )
        display(w)
 
        clear_output()
        display_task()
        loesung_gefunden=True
        for i in range(3):
            if z[i,0]!=int(text[i].value):
               loesung_gefunden=False
               break
        if loesung_gefunden:
                display(HTML("<b><font color='green'>Richtig</font></b>"))
        else:
                display(HTML("<b><font color='red'>Falsch</font></b>"))
 
 
def exec_la_scalar_1():
        init_vectors(button2)
        button2.on_click(init_vectors)
        button1.on_click(evaluate)
        display(widgets.VBox(mhbox1))
        display(widgets.VBox(cb_container[0]))
        display(widgets.VBox(mhbox2))

Die Zeile cb_container[j].children= funktioniert nicht. Es kommt folgende Fehlermeldung:

TraitError: The 'children' trait of a FlexBox instance must be a tuple, but a value of class 'ipywidgets.widgets.widget_box.FlexBox' (i.e. <ipywidgets.widgets.widget_box.FlexBox object at 0x7f2abf20c9b0>) was specified.


Wenn ich cb_container nicht als Feld/Liste definiere dann funktioniert der Code. Woran liegt das?
Brando
User
Beiträge: 171
Registriert: Donnerstag 28. Januar 2016, 15:36

Mein Mustercode lautet wie folgt und er funktioniert:

Code: Alles auswählen

%matplotlib notebook
import pandas as pd
import matplotlib.pyplot as plt
from ipywidgets import *
from IPython.display import display
from IPython.html import widgets
plt.style.use('ggplot')

NUMBER_OF_PINGS = 4

# displaying the text widget
text = widgets.Text(description="Domain to ping", width=200)
display(text)

# preparing the plot 
data = pd.DataFrame()
x = range(1,NUMBER_OF_PINGS+1)
plots = dict()
fig, ax = plt.subplots()
plt.xlabel('iterations')
plt.ylabel('ms')
plt.xticks(x)
plt.show()

# preparing a container to put in created checkbox per domain
checkboxes = []
cb_container = widgets.HBox()
display(cb_container)

# add button that updates the graph based on the checkboxes
button = widgets.Button(description="Update the graph")

# function to deal with the added domain name
def handle_submit(sender):
    # a part of the magic inside python : pinging
    res = !ping -c {NUMBER_OF_PINGS} {text.value}
    hits = res.grep('64 bytes').fields(-2).s.replace("time=","").split()
    if len(hits) == 0:
        print "Domain gave error on pinging"
    else:
         # rebuild plot based on ping result
        data[text.value] = hits
        data[text.value] = data[text.value].astype(float)
        plots[text.value], = ax.plot(x, data[text.value], label=text.value)
        plt.legend()
        plt.draw()
        # add a new checkbox for the new domain
        checkboxes.append(widgets.Checkbox(description = text.value, value=True, width=90))
        cb_container.children=[i for i in checkboxes]
        if len(checkboxes) == 1:
            display(button)

# function to deal with the checkbox update button       
def on_button_clicked(b):
    for c in cb_container.children:
        if not c.value:
            plots[c.description].set_visible(False)
        else:
            plots[c.description].set_visible(True)
    plt.legend()
    plt.draw()

button.on_click(on_button_clicked)
text.on_submit(handle_submit)
plt.show()
Antworten