Change button name on ipywidgets - widget

Is there a way to easily change the button name in the ipywidgets module? I am using the decorator, but cannot find in the documentation how to change the name to something other than "Run Interact". I believe I need to use the decorator since my function needs to be run on demand and depends on multiple inputs from different widgets, but I'm open to other ways of doing so as well.
import ipywidgets as widgets
from IPython.display import display
#widgets.interact_manual(number1 = widgets.Dropdown(
options=[1,2],
description='select a number'),
number2 = widgets.Dropdown(
options=[3,4],
description='select another number'))
def add_numbers(number1,number2):
return number1+number2

A bit quick and dirty but you can set
widgets.interact_manual.opts['manual_name'] = 'Your text here'
before defining your function and this should change the label name. If you have multiple interact_manual calls that need different labels you will need to change it each time.
import ipywidgets as widgets
from IPython.display import display
widgets.interact_manual.opts['manual_name'] = 'Your text here'
#widgets.interact_manual(number1 = widgets.Dropdown(
options=[1,2],
description='select a number'),
number2 = widgets.Dropdown(
options=[3,4],
description='select another number'),)
def add_numbers(number1,number2):
return number1+number2

Related

Change C++ display text with HTML txt file?

I want to be able to change C++ display text from an HTML txt file, is this possible to do?
your issue is your using pack and grid. pack and grid do the same thing but grid lets you choose where to put it. you can only use one or the other in a canvas. also you had hello and goodbye in the same spot on grid(). heres your fixed code:
from tkinter import *
from tkinter import ttk
label = None
def change1():
global label
label.config(text="Hello World!")
def change2():
global label
label.config(text="Goodbye World!")
def main():
global label
rootWindow = Tk()
label = ttk.Label(rootWindow, text="Hello World!")
label.grid(row=0, column=0)
button1 = ttk.Button(rootWindow, text="Hello!", command=change1)
button1.grid(row=0, column=1)
button2 = ttk.Button(rootWindow, text="Bye!", command=change2)
button2.grid(row=0, column=2)
rootWindow.mainloop()
main()
your problem is that you are using both .grid() and .pack() the difference is that in .grid you can choose where to put your button or whatever while in .pack() it places it automatically. this is why I will recommend you to use the .grid() option.

calling a function which shows sub category list in a select box using observe function is working only first time

I have simple df have main category and its sub items. I made two select boxes to select main category and it automatically shows belonged items at the other select box using 'observe'
But it works only at the first time category selection and after I selected another category it didn't show sub items in an another select box.
If i put 'observe' inside the 'def' the function is worked as I wanted.
But this approach is troublesome if I have many other 'def' executing on observe on change.
I am also looking for the way to make this code simple without using global.
And also welcome any ideas to make this code simpler and lighter.
import pandas as pd
import ipywidgets as wg
from ipywidgets import *
from IPython.display import display, clear_output
df_list=[{'Category':'fruit','name':['banana','apple','mango']},\
{'Category':'animal','name':['lion','monkey','tiger','cat','dog']},\
{'Category':'body','name':['eyes','hands','ears','arms']},\
{'Category':'office','name':['table','computer','printer']}]
df=pd.DataFrame(df_list)
Category_box=wg.Select(options=list(df.Category),continuous_update=False,layout=Layout(width='30%'))
name_box=wg.Select(options=list(df[df['Category']==Category_box.value].name)[0],continuous_update=False,\
layout=Layout(width='30%'))
hbox=wg.HBox(children=[Category_box,name_box])
display(hbox)
def select_on_change(change):
if change['name'] == 'value':
global Category_box
global name_box
global hbox
Category_box=wg.Select(options=list(df.Category),continuous_update=False,layout=Layout(width='30%'),value=Category_box.value)
name_box=wg.Select(options=list(df[df['Category']==Category_box.value].name)[0],continuous_update=False,\
layout=Layout(width='30%'))
hbox=wg.HBox(children=[Category_box,name_box])
clear_output()
display(hbox)
#Category_box.observe(select_on_change)
Category_box.observe(select_on_change)
Firstly, thanks for the complete and clear example.
The solution is to not create new widgets in your function that you are observing. Instead just update the .options of your name_box widget. This way, no globals required.
import pandas as pd
import ipywidgets as wg
from ipywidgets import *
from IPython.display import display, clear_output
df_list=[{'Category':'fruit','name':['banana','apple','mango']},\
{'Category':'animal','name':['lion','monkey','tiger','cat','dog']},\
{'Category':'body','name':['eyes','hands','ears','arms']},\
{'Category':'office','name':['table','computer','printer']}]
df=pd.DataFrame(df_list)
Category_box=wg.Select(options=list(df.Category),continuous_update=False,layout=Layout(width='30%'))
name_box=wg.Select(options=list(df[df['Category']==Category_box.value].name)[0],continuous_update=False,\
layout=Layout(width='30%'))
hbox=wg.HBox(children=[Category_box,name_box])
display(hbox)
def select_on_change(change):
if change['name'] == 'value':
name_box.options = list(df[df['Category']==Category_box.value].name)[0]
Category_box.observe(select_on_change)

IPython notebook widgets using interactive

I'm having trouble creating widgets in a Jupyter notebook that update when other widget values are changed. This is the code I've been playing around with:
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
from IPython.display import display
def func(arg1,arg2):
print arg1
print arg2
choice = widgets.ToggleButtons(description='Choice:',options=['A','B'])
display(choice)
metric = widgets.Dropdown(options=['mercury','venus','earth'],description='Planets:')
text = widgets.Text(description='Text:')
a = interactive(func,
arg1=metric,
arg2=text,
__manual=True)
def update(*args):
if choice.value == 'A':
metric = widgets.Dropdown(options=['mercury','venus','earth'],description='Planets:')
text = widgets.Text(description='Text:')
a.children = (metric,text)
else:
metric = widgets.Dropdown(options=['monday','tuesday','wednesday'],description='Days:')
text2 = widgets.Textarea(description='Text2:')
a.children = (metric,text2)
choice.observe(update,'value')
display(a)
The resulting widgets metric and text do change based whether A or B is selected, but the problem is that the "Run func" button goes away as soon as I change to B. I've tried adding the __manual attribute immediately before display(a), adding it within update, and several other places. How do I change the children of the widget box without overwriting the fact that I want to manually run the function?

How do I rerender HTML PyQt4

I have managed to use suggested code in order to render HTML from a webpage and then parse, find and use the text as wanted. I'm using PyQt4. However, the webpage I am interested in is updated frequently and I want to rerender the page and check the updated HTML for new info.
I thus have a loop in my pythonscript so that I sort of start all over again. However, this makes the program crash. I have searched the net and found out that this is to be expected, but I have not found any suggestion on how to do it correctly. It must be simple, I guess?
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
class Render (QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
r = Render(url)
html = r.frame.toHtml()
S,o when I hit r=Render(url) the second time, it crashes. S,o I am looking for something like r = Rerender(url).
As you might guess, I am not much of a programmer, and I usually get by by stealing code I barely understand. But this is the first time I can't find an answer, so I thought I should ask a question myself.
I hope my question is clear enough and that someone has the answer.
Simple demo (adapt to taste):
import sys, signal
from PyQt4 import QtCore, QtGui, QtWebKit
class WebPage(QtWebKit.QWebPage):
def __init__(self, url):
super(WebPage, self).__init__()
self.url = url
self.mainFrame().loadFinished.connect(self.handleLoadFinished)
self.refresh()
def refresh(self):
self.mainFrame().load(QtCore.QUrl(self.url))
def handleLoadFinished(self):
print('Loaded:', self.mainFrame().url().toString())
# do stuff with html ...
print('Reloading in 3 seconds...\n')
QtCore.QTimer.singleShot(2000, self.refresh)
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QtGui.QApplication(sys.argv)
webpage = WebPage('http://en.wikipedia.org/')
print('Press Ctrl+C to quit\n')
sys.exit(app.exec_())

Remove a label with function arguments tkinter

I am trying to remove a label in tkinter, but I can't seem to get it to work.
self.label(text='message')
self.label.grid(row=1,column=1)
def removelabel(labelname):
labelname.grid_remove()
removelabel(self.label)
You have to save a reference to the widget, which requires to to create the widget and lay it out in two steps:
self.label = tk.Label(...)
self.label.grid(row=1, column=1)
...
def removelabel(label):
label.grid_remove()
...
removelabel(self.label)