text wrapping in ipywidgets - word-wrap

I can't seem to get my widgets to wrap text.
This code:
import ipywidgets as widgets
test_layout = widgets.Layout(
border='1px solid black',
flex_flow = 'row wrap',
width = '200px')
test_string = 'test test test test test test test test test test'
test_label = widgets.Label(value = test_string, layout=test_layout)
test_label
Outputs:
What am I missing? I have tried lots of different things, but none of them have worked!

I had the same issue. I used an HTML widget instead like this:
import ipywidgets as widgets
widget = widgets.HTML(value= '<style>p{word-wrap: break-word}</style> <p>'+ [variable containing long text goes here] +' </p>')

You may increase width = '400px')

Related

How to set fixed width/height in Enaml grid container

I have just come across Enaml for python GUI programming. I only used PySide2 once before for a simple calculator GUI mockup, so I'm new to both Qt and Enaml. Forgive my ignorance ;)
Essentially, I want to have a regular grid of Field or other elements, with fixed, square sizes. After going over some of the examples, I came up with:
from enaml.layout.api import grid
from enaml.widgets.api import Window, Container, Field
enamldef DigitField(Field):
# The fields will contain a single digit for testing.
mask = 'D'
max_length = 1
# These don't have any effect?
hug_width = 'required'
hug_height = 'required'
enamldef Main(Window):
Container:
constraints = [
grid(
[f11, f12],
[f21, f22],
),
]
DigitField: f11:
text = '1'
DigitField: f12:
text = '1'
DigitField: f21:
text = '1'
DigitField: f22:
text = '1'
But the hug_width and hug_height don't seem to work. I then tried manually setting f11.width == 50, for example, inside the constraints, but the kiwisolver shouts at me about unresolvable constraints. I tried everything I could find from the examples about setting width values, but stuff that works for vbox doesn't seem to play with grid.
Any ideas? Also, if someone has a full app made with Enaml, that is open source, I would love to take a look. The docs are OK but some more advanced examples would be awesome.
Well, I think I have found a way to make it work. hug_width restricts width to the field content plus some default padding (from the Qt toolkit). Instead, using resist_width = 'ignore' I was able to completely remove the padding. The grid can be generated using a manual or an automatic method.
The manual method:
from enaml.layout.api import grid
from enaml.widgets.api import Window, Container, Field
enamldef DigitField(Field):
# The fields will contain a single digit for testing.
mask = 'D'
max_length = 1
resist_width = 'ignore'
resist_height = 'ignore'
enamldef Main(Window):
Container:
constraints = [
grid(
[f11, f12],
[f21, f22],
),
f11.width == f11.height,
f12.width == f12.height,
]
DigitField: f11:
text = '1'
DigitField: f12:
text = '1'
DigitField: f21:
text = '1'
DigitField: f22:
text = '1'
This is too WET and scales horribly, so instead we have...
The factory method:
from itertools import zip_longest
from enaml.core.api import Include
from enaml.layout.api import align, grid, factory
from enaml.widgets.api import Window, Container, Field
enamldef DigitField(Field):
mask = 'D'
max_length = 1
resist_width = 'ignore'
resist_height = 'ignore'
def generate_grid(container, num_cols):
rows = []
widgets = container.visible_widgets()
row_iters = (iter(widgets),) * num_cols
rows = list(zip_longest(*row_iters))
return [grid(*rows), align('width', *widgets)]
enamldef Main(Window):
Container:
Container:
constraints << [factory(generate_grid, 3)]
Include:
objects << [DigitField(text=str(1)) for i in range(9)]
I have nested the Container because there will probably be other things in the main window as well, and Enaml windows require a single master Container.

Adjust a Bokeh DataTable to the window

I would like to automatically adjust the width of a bokeh DataTable to the size of a screen. But I do not find the right way to do it. This line of code is supposed to work :
data_table = DataTable(source=source, columns=columns, height = 300, sizing_mode = 'scale_width', fit_columns=True)
But it does not. My Datatable keeps the same width.
Does anyone know how to solve this problem ?
Thank you.
I'm afraid it's not possible with the current implementation of DataTable - if you don't specify an explicit width in pixels, the width will be set to 600px.
You're welcome to create a feature request on Bokeh's GitHub.
As of 2.2.3 and likely earlier you can use sizing_mode:
import pandas as pd, numpy as np, random, string
from bokeh.models import ColumnDataSource, DataTable, TableColumn
from bokeh.plotting import show
df = pd.DataFrame(np.random.randint(0,100,size=(100, 12)), columns=[(random.randint(1,30) * random.choice(string.ascii_uppercase)) for col in range(12)])
data_table = DataTable(columns = [TableColumn(field=c, title=c) for c in df.columns], sizing_mode='stretch_width', source = ColumnDataSource(df))
show(data_table)

How do I retrieve a specific image from a specific link? (Programming Beginner)

I'm a programming beginner - so apologies if this question is not appropriate. I have tried my best to search the internet for an answer for the better part of today.
I'm trying to retrieve the image from this link: http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992
I am using the code below: (I know it fetches all of the images.)
My question is - why does this code work on this link: http://www.imdb.com/title/tt0076759/?ref_=nv_sr_5 but not on this link: http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992 ?
import urllib2
import os
from BeautifulSoup import BeautifulSoup
URL = "http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992"
default_dir = os.path.join(os.path.expanduser("~"),"Pictures")
opener = urllib2.build_opener()
urllib2.install_opener(opener)
soup = BeautifulSoup(urllib2.urlopen(URL).read())
imgs = soup.findAll("img",{"alt":True, "src":True})
for img in imgs:
img_url = img["src"]
filename = os.path.join(default_dir, img_url.split("/")[-1])
img_data = opener.open(img_url)
f = open(filename,"wb")
f.write(img_data.read())
f.close()
I would like to fetch the image from this link: http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992
I am currently getting no images with the above code from this link. It works with other links though.
this is because the img tags inside that url don't have the alt attribute, which you are defining for filtering those img tags with:
imgs = soup.findAll("img",{"alt":True, "src":True})
that list returns empty.

Link a tkinter button to seperate script

I have a tkinter interface with a few entry widgets as inputs. Upon clicking a button I would like those inputs to be sent to a separate script to be processed and a value printed and potentially returned back to the button (I am looking at this for a dual accuracy assessment statistic)
This is a lower scale example of what I have so far and am looking to accomplish
Example Secondary Script: GUI_ConnectorScript
def calculate():
global result
result = int(entry.get())
result += 1
print result
Primary Script: GUI_ConnectorScript
from Tkinter import *
import GUI_ConnectorScript
background = "#A8A8A8"
master = Tk()
screen_width = master.winfo_screenwidth()
screen_height = master.winfo_screenheight()
width = int(screen_width*0.7)
height = int(screen_height*0.7)
size = "%sx%s"%(width,height)
master.geometry(size)
master.title("GIS Display")
text = Text(master, width = 80, height = 40, background = background)
text.pack(expand = TRUE, fill = BOTH)
entry = Entry(master, width=5).place(x=100,y=100)
button = Button(master, text="Calculate", command=GUI_ConnectorScript).place(x=500,y=500)
mainloop()
I have been trying to figure this out for awhile and have look around a lot for an answer. I have found examples similar but I am having an issue getting it to work for my application.
I agree with Parviz, whenever GUI programs get too complicated you should use Object-Oriented Programming.
I can further advice that you use kivy (if possible) instead of tkinter, its much better for bigger projects

Refresh image in Tkinter window

I am building an application to continuously display an image fetched from an IP camera. I have figured out how to fetch the image, and how to also display the image using Tkinter. But I cannot get it to continuously refresh the image. Using Python 2.7+.
Here is the code I have so far.
import urllib2, base64
from PIL import Image,ImageTk
import StringIO
import Tkinter
URL = 'http://myurl.cgi'
USERNAME = 'myusername'
PASSWORD = 'mypassword'
def fetch_image(url,username,password):
# this code works fine
request = urllib2.Request(url)
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
imgresp = result.read()
img = Image.open(StringIO.StringIO(imgresp))
return img
root = Tkinter.Tk()
img = fetch_image(URL,USERNAME,PASSWORD)
tkimg = ImageTk.PhotoImage(img)
Tkinter.Label(root,image=tkimg).pack()
root.mainloop()
How should I edit the code so that the fetch_image is called repeatedly and its output updated in the Tkinter window?
Note that I am not using any button-events to trigger the image refresh, rather it should be refreshed automatically, say, every 1 second.
Here is a solution that uses Tkinter's Tk.after function, which schedules future calls to functions. If you replace everything after your fetch_image definition with the snipped below, you'll get the behavior you described:
root = Tkinter.Tk()
label = Tkinter.Label(root)
label.pack()
img = None
tkimg = [None] # This, or something like it, is necessary because if you do not keep a reference to PhotoImage instances, they get garbage collected.
delay = 500 # in milliseconds
def loopCapture():
print "capturing"
# img = fetch_image(URL,USERNAME,PASSWORD)
img = Image.new('1', (100, 100), 0)
tkimg[0] = ImageTk.PhotoImage(img)
label.config(image=tkimg[0])
root.update_idletasks()
root.after(delay, loopCapture)
loopCapture()
root.mainloop()

Resources