I am having a issue with size of the second graph added to the tab widget, which is not of the size of all the container:
here is by code
''' output_co2 = widgets.Output()
output_co = widgets. Output()
tab = widgets.Tab(children=[output_co2, output_co],
layout=widgets.Layout(width='100%', height='100%'))
tab.set_title(0, 'CO2')
tab.set_title(1, 'CO')
display(tab)
with output_co2:
fig = go.Figure()
fig.add_trace(go.Scatter(x=vehicleData['distance_m']/1000,
y=vehicleData['co_gs'],
name='CO [g/s]',
mode="lines",
line=dict(
width=2),
fig.show()
with output_co:
fig = go.Figure()
fig.add_trace(go.Scatter(x=vehicleData['distance_m']/1000,
y=vehicleData['co_gs'],
name='CO [g/s]',
mode="lines",
line=dict(
width=2),
fig.show() '''
enter image description here
enter image description here
With plotly you need to use the go.FigureWidget() in place of go.Figure(), see here. So something like this:
output_co2 = widgets.Output()
output_co = widgets.Output()
tab = widgets.Tab(children=[output_co2, output_co])
tab.set_title(0, 'CO2')
tab.set_title(1, 'CO')
display(tab)
with output_co2:
fig = go.FigureWidget() # HERE
fig.add_trace(go.Scatter(x=vehicleData['distance_m']/1000,
y=vehicleData['co_gs'],
name='CO [g/s]',
mode="lines",
line_width=2))
fig.show()
with output_co:
fig = go.FigureWidget() # AND HERE
fig.add_trace(go.Scatter(x=vehicleData['distance_m']/1000,
y=vehicleData['co_gs'],
name='CO [g/s]',
mode="lines",
line_width=2))
fig.show()
Alternative:
With plotly you can use go.FigureWidget() directly instead of widgets.Output()
fig1 = go.FigureWidget()
fig2 = go.FigureWidget()
tab = widgets.Tab(children=[fig1, fig2])
tab.set_title(0, 'CO2')
tab.set_title(1, 'CO')
fig1.add_trace(go.Scatter(x=vehicleData['distance_m']/1000,
y=vehicleData['co_gs'],
mode="lines",
line_width=2))
fig2.add_trace(go.Scatter(x=vehicleData['distance_m']/1000,
y=vehicleData['co_gs'],
mode="lines",
line_width=2))
display(tab)
Related
The image shows the GUI:
I am making a GUI with Tkinter which can show graphs which have been plotted with matplotlib.
The graphs get their x and y values from a JSON file.
The data from the JSON file gets collected by some code which I wrote (this code is included in the code below)
What works: The collecting of data from the JSON-file, plotting the data in a graph via matplotlib, and showing this graph on a tkinter canvas all works fine.
Problem: I cannot clear the canvas, such that I can display another graph based on data from another JSON file. I have to close the program, start it again, and select a different JSON file, if I want to see another graph.
Here is the code:
################################### GUI program for graphs #######################################
##### Scrollbar for the listbox #####
Myframe = Frame(inspect_data)
Myframe.pack(side=tk.LEFT, fill=Y)
my_scrollbar = Scrollbar(Myframe, orient=VERTICAL)
#####Listbox#####
vores_listebox = Listbox(Myframe, width=22, height=40,
yscrollcommand=my_scrollbar.set)
vores_listebox.pack(side=LEFT, expand=True)
my_scrollbar.config(command=vores_listebox.yview)
my_scrollbar.pack(side=LEFT, fill=Y)
Myframe.pack()
###### Button functions ######
path_us = ""
def vis_NS():
vores_listebox.delete(0, END)
# Husk at ændre mapper##
global path_us
path_us = "C://Users//canal//OneDrive//Dokumenter//AAU//3. semester//1//"
for x in os.listdir(path_us):
if x.endswith(".json"):
vores_listebox.insert(END, x)
def vis_OS():
global path_us
path_us = "C://Users//canal//OneDrive//Dokumenter//AAU//3. semester//2//"
vores_listebox.delete(0, END)
# De NS;OS,US,MS skal ligge i hver sin mappe#
for x in os.listdir(path_us):
if x.endswith(".json"):
vores_listebox.insert(END, x)
def vis_US():
vores_listebox.delete(0, END)
for x in os.listdir("C://Users//canal//OneDrive//Dokumenter//AAU//3. semester//2"):
if x.endswith(".json"):
vores_listebox.insert(END, x)
def vis_MS():
vores_listebox.delete(0, END)
for x in os.listdir("C://Users//canal//OneDrive//Dokumenter//AAU//3. semester//2"):
if x.endswith(".json"):
vores_listebox.insert(END, x)
#### Buttons #####
button1 = Button(inspect_data,
text="Normal screwing",
width=17,
height=2,
bg="white",
fg="black",
command=vis_NS
)
button1.place(x=5, y=10)
button2 = Button(inspect_data,
text="Over screwing",
width=17,
height=2,
bg="white",
fg="black",
command=vis_OS
)
button2.place(x=5, y=50)
button3 = Button(inspect_data,
text="Under screwing",
width=17,
height=2,
bg="white",
fg="black",
command=vis_US
)
button3.place(x=5, y=90)
button4 = Button(inspect_data,
text="Missing screw",
width=17,
height=2,
bg="white",
fg="black",
command=vis_MS
)
button4.place(x=5, y=130)
######en fil bliver trykket#####
# placing the canvas on the Tkinter window
def items_selected(event):
selected_indices = vores_listebox.curselection()
selected_json = ",".join([vores_listebox.get(i) for i in selected_indices])
full_file_path = path_us + selected_json
open_json = js.load(open(full_file_path, "r"))
time = [open_json['XML_Data']
['Wsk3Vectors']['X_Axis']['Values']['float']]
rpm = [open_json['XML_Data']['Wsk3Vectors']
['Y_AxesList']['AxisData'][0]['Values']['float']]
torque = [open_json['XML_Data']['Wsk3Vectors']
['Y_AxesList']['AxisData'][1]['Values']['float']]
current = [open_json['XML_Data']['Wsk3Vectors']
['Y_AxesList']['AxisData'][2]['Values']['float']]
angle = [open_json['XML_Data']['Wsk3Vectors']
['Y_AxesList']['AxisData'][3]['Values']['float']]
depth = [open_json['XML_Data']['Wsk3Vectors']
['Y_AxesList']['AxisData'][4]['Values']['float']]
####### Using Matlib.pyplot to plot 5 graphs #######
plt.rcParams["figure.figsize"] = (7, 10)
plt.subplot(5, 1, 1)
plt.scatter(time, rpm, c="b", linewidths=2,
marker=",", edgecolor="b", s=1, alpha=0.5)
plt.title(selected_json)
plt.gca().axes.xaxis.set_ticklabels([])
plt.ylabel("RPM")
plt.grid()
plt.subplot(5, 1, 2)
plt.scatter(time, torque, c="g", linewidths=1,
marker=",", edgecolor="g", s=1, alpha=0.3)
plt.gca().axes.xaxis.set_ticklabels([])
plt.ylabel("Torque [Nm]")
plt.grid()
plt.subplot(5, 1, 3)
plt.scatter(time, current, c="r", linewidths=2,
marker=",", edgecolor="r", s=1, alpha=0.5)
plt.gca().axes.xaxis.set_ticklabels([])
plt.ylabel("Current [Amps]")
plt.grid()
plt.subplot(5, 1, 4)
plt.scatter(time, angle, c="m", linewidths=2,
marker=",", edgecolor="m", s=1, alpha=0.5)
plt.gca().axes.xaxis.set_ticklabels([])
plt.ylabel("Angle [RAD]")
plt.grid()
plt.subplot(5, 1, 5)
plt.scatter(time, depth, c="c", linewidths=2,
marker=",", edgecolor="c", s=1, alpha=0.5)
plt.xlabel("Time [ms]")
plt.ylabel("Depth [mm]")
plt.grid()
#### Sowing all the subplots in a tkinter canvas ########
fig = plt.figure()
canvas = FigureCanvasTkAgg(fig, master=inspect_data)
canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# toolbar = matplotlib.NavigationToolbar2TkAgg(
# canvas, self)
# toolbar.update()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
vores_listebox.bind('<<ListboxSelect>>', items_selected)
root.after(1000, converter)
root.mainloop()
I have tried canvas.delete(all), plt.clf() among other things. One solution I think could work is:
If I start the function def items_selected to clear the figure inside the canvas by using: plt.clf(fig), however "fig" is not defined at this point, so python wouldn't know what this means.
it seems to me that the problem originates from plotting to plt, and not directly onto some axis from a figure linked to tkinter. Try to bind your subplot figure directly to your canvas outside the items_selected() function, and then redraw the canvas whenever you change the underlying matplotlib figure:
fig, axes = plt.subplots(5, 1, figsize=(7, 10))
canvas = FigureCanvasTkAgg(fig, inspect_data)
canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
def items_selected(event):
.....
axes[0].scatter(time, rpm, c="b", linewidths=2,
marker=",", edgecolor="b", s=1, alpha=0.5)
axes[0].set_title(selected_json)
axes[0].set_xticklabels([])
axes[0].set_ylabel("RPM")
axes[0].grid()
....
canvas.draw()
Hello I'm using Google colab to display multiplot that's why I tried to create one scatterplot with 3 scatter in it and under that, there is a parallel categories plot that should be connected to scatter but when I try to select a group of points in scatter, I cannot change color in parcat it's always grey, I think those functions such as on_click and on_selection does not work but I couldn't replace them with another code can someone help me?
import plotly.graph_objects as go
from ipywidgets import widgets
import pandas as pd
import numpy as np
# Build parcats dimensions
#here dfTot is my big class include every layer(input,1,2,3,output)
#Check image under the Code
dfTot = pd.concat([df1,df2,df3,df4], axis=1,join='inner')
categorical_dimensions = ['Layer Input', 'Layer 2', 'Layer 3','Layer Output'];
dimensions = [dict(values=dfTot[label], label=label) for label in categorical_dimensions]
# Build colorscale
color = np.zeros(len(dfTot), dtype='uint8')
colorscale = [[0, 'gray'], [1, 'firebrick']]
# Build figure as FigureWidget
fig = go.FigureWidget(
data=[
go.Scatter(x=layer_activation1[:,0], y=layer_activation1[:,1],showlegend = False,hovertemplate =y+"<br>"+"Cluster Groupe : "+df2['Layer 2']+"<br>"+"Layer 2"'<extra></extra>',
marker={'color': 'gray'}, mode='markers', selected={'marker': {'color': 'firebrick'}},
unselected={'marker': {'opacity': 0.3}}),
go.Scatter(x=layer_activation2[:,0], y=layer_activation2[:,1],showlegend = False,hovertemplate =y+"<br>"+"Cluster Groupe : "+df3['Layer 3']+"<br>"+"Layer 3"'<extra></extra>',
marker={'color': 'gray'}, mode='markers', selected={'marker': {'color': 'firebrick'}},
unselected={'marker': {'opacity': 0.3}}),
go.Scatter(x=layer_activation3[:,0], y=layer_activation3[:,1],showlegend = False,hovertemplate =y+"</br>"+"Cluster Groupe : "+df4['Layer Output']+"<br>"+"Layer Output"'<extra></extra>',
marker={'color': 'gray'}, mode='markers', selected={'marker': {'color': 'firebrick'}},
unselected={'marker': {'opacity': 0.3}}),
go.Parcats(
domain={'y': [0, 0.4]}, dimensions=dimensions,
line={'colorscale': colorscale, 'cmin': 0,
'cmax': 1, 'color': color, 'shape': 'hspline'})
])
fig.update_layout(
height=800, xaxis={'title': 'Axis x'},
yaxis={'title': 'Axis y', 'domain': [0.6, 1]},
dragmode='lasso', hovermode='closest')
# Update color callback
def update_color(trace, points, state):
new_color = np.zeros(len(dfTot), dtype='uint8')
# Update scatter selection
fig.data[0].selectedpoints = points.point_inds
new_color[points.point_inds] = 1
fig.data[3].line.color = new_color
fig.data[1].selectedpoints = points.point_inds
new_color[points.point_inds] = 1
fig.data[3].line.color = new_color
fig.data[2].selectedpoints = points.point_inds
# Update parcats colors
new_color[points.point_inds] = 1
fig.data[3].line.color = new_color
# Register callback on scatter selection...
fig.data[0].on_selection(update_color)
fig.data[1].on_selection(update_color)
fig.data[2].on_selection(update_color)
# and parcats click
fig.data[3].on_click(update_color)
Here is the screenshot of plot
I'm newbie in web scraping. I know how to get data from an HTML or from a JSON but there is a place where I can't know how to do it. I would like to get the positions of points and X's that you can see in the short chart of this page.
http://www.fiba.basketball/euroleaguewomen/18-19/game/2410/Nadezhda-ZVVZ-USK-Praha#|tab=shot_chart
How can I do that?
I'm fairly new as well, but learning as I go. It looks like this page is dynamic, so you'd need to use Selenium to load the page first, before grabbing the html with beautifulsoup to get the x and y coordinates from the Made Shots and Missed shots. So I gave it a shot and was able to get a dataframe with the x, y coords along with if it was 'made' or 'miss'.
I plotted it afterwards just to check to see if it matched, and it appears to be flipped about the x-axis. I believe this is because when you plot on a chart like this graphically, the top, left corner is your (0,0). So your y coordinates are going to be opposite when you want to plot it. I could be wrong though.
None the less, here's the code I used.
import pandas as pd
import bs4
from selenium import webdriver
driver = webdriver.Chrome('C:\chromedriver_win32\chromedriver.exe')
driver.get('http://www.fiba.basketball/euroleaguewomen/18-19/game/2410/Nadezhda-ZVVZ-USK-Praha#|tab=shot_chart')
html = driver.page_source
soup = bs4.BeautifulSoup(html,'html.parser')
made_shots = soup.findAll("svg", {"class": "shot-hit icon icon-point clickable"})
missed_shots = soup.findAll("svg", {"class": "shot-miss icon icon-miss clickable"})
def get_coordiantes(element, label):
results = pd.DataFrame()
for point in element:
x_point = float(point.get('x'))
y_point = float(point.get('y'))
marker = label
temp_df = pd.DataFrame([[x_point, y_point, marker]], columns=['x','y','marker'])
results = results.append(temp_df)
return results
made_results = get_coordiantes(made_shots, 'made')
missed_results = get_coordiantes(missed_shots, 'missed')
results = made_results.append(missed_results)
results = results.reset_index(drop=True)
results['y'] = results['y'] * -1
driver.close()
gives this output:
In [6]:results.head(5)
Out[6]:
x y marker
0 33.0 -107.0 made
1 159.0 -160.0 made
2 143.0 -197.0 made
3 38.0 -113.0 made
4 65.0 -130.0 made
and when I plot it:
import seaborn as sns
import numpy as np
# Add a column: the color depends of x and y values, but you can use whatever function.
value=(results['marker'] == 'made')
results['color']= np.where( value==True , "green", "red")
# plot
sns.regplot(data=results, x="x", y="y", fit_reg=False, scatter_kws={'facecolors':results['color']})
ADDITIONAL: I'm sure there's a better, more efficient, cleaner way to code this up. But just doing it on the fly, came up with this. It should get you going. Feel free to dive into it and look at the html source code to start seeing how it's grabbing the different data. have fun.
import pandas as pd
import bs4
from selenium import webdriver
driver = webdriver.Chrome('C:\chromedriver_win32\chromedriver.exe')
driver.get('http://www.fiba.basketball/euroleaguewomen/18-19/game/2410/Nadezhda-ZVVZ-USK-Praha#|tab=shot_chart')
html = driver.page_source
soup = bs4.BeautifulSoup(html,'html.parser')
###############################################################################
shots = soup.findAll("g", {"class": "shot-item"})
results = pd.DataFrame()
for point in shots:
hit = point.get('data-play-by-play-action-hit')
action_id = point.get('data-play-by-play-action-id')
period = point.get('data-play-by-play-action-period')
player_id = point.get('data-play-by-play-action-player-id')
team_id = point.get('data-play-by-play-action-team-id')
x_point = float(point.find('svg').get('x'))
y_point = float(point.find('svg').get('y'))
temp_df = pd.DataFrame([[hit, action_id, period, player_id, team_id, x_point, y_point]],
columns=['hit','action_id','period','player_id','team_id','x','y'])
results = results.append(temp_df)
results['y'] = results['y'] * -1
results = results.reset_index(drop=True)
###############################################################################
player_ids = soup.findAll('label', {"class": "item-label"})
players = pd.DataFrame()
for player in player_ids:
player_id = player.find('input').get('data-play-by-play-action-player-id')
if player_id == None:
continue
player_name = player.find('span').text
temp_df = pd.DataFrame([[player_id, player_name]],
columns=['player_id','player_name'])
players = players.append(temp_df)
players = players.reset_index(drop=True)
###############################################################################
team_ids = soup.findAll('div', {"class": "header-scores_desktop"})
teams_A = team_ids[0].find('div', {"class": "team-A"})
team_id_A = teams_A.find('img').get('src').rsplit('/')[-1]
team_name_A = teams_A.find('span').text
teams_B = team_ids[0].find('div', {"class": "team-B"})
team_id_B = teams_B.find('img').get('src').rsplit('/')[-1]
team_name_B = teams_B.find('span').text
teams = pd.DataFrame([[team_id_A, team_name_A],[team_id_B,team_name_B]],
columns=['team_id','team_name'])
teams = teams.reset_index(drop=True)
###############################################################################
actions = pd.DataFrame()
action_ids = soup.findAll('div', {"class": "overlay-wrapper"})
for action in action_ids:
action_id = action.get('data-play-by-play-action-id')
time_remaining = action.find('div').find('span', {'class': 'time'}).text
full_name = action.find('div').find('span', {'class': 'athlete-name'}).text
if not action.find('div').find('span', {'class': 'action-code'}):
result_of_action = '+0'
else:
result_of_action = action.find('div').find('span', {'class': 'action-code'}).text
action_description = action.find('div').find('span', {'class': 'action-description'}).text
team_A_score = action.find('div').find('span', {'class': 'team-A'}).text
team_B_score = action.find('div').find('span', {'class': 'team-B'}).text
temp_df = pd.DataFrame([[action_id, time_remaining, full_name, result_of_action, team_A_score, team_B_score, action_description]],
columns=['action_id','time_remaining', 'full_name', 'result_of_action', team_name_A+'_score', team_name_B+' score', 'action-description'])
actions = actions.append(temp_df)
actions = actions.reset_index(drop=True)
###############################################################################
results = pd.merge(results, players, how='left', on='player_id')
results = pd.merge(results, teams, how='left', on='team_id')
results = pd.merge(results, actions, how='left', on='action_id')
driver.close()
And to clean it a bit, you can sort the rows so that they are in order, play-by-play from start to finish
results.sort_values(['period', 'time_remaining'], ascending=[True, False], inplace=True)
results = results.reset_index(drop=True)
when I am using the API of Object_detection,I followed the instruction ,everything is fine .However ,when I begin to test my picture , I met a problem , it seems that the function named
" visualize_boxes_and_labels_on_image_array " ( in the 57 line ) didn't work . Here is my source codes
import cv2
import numpy as np
import tensorflow as tf
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
class TOD(object):
def __init__(self):
self.PATH_TO_CKPT = '/home/xiyou/Desktop/ssd_training/result/frozen_inference_graph.pb'
self.PATH_TO_LABELS = '/home/xiyou/Desktop/ssd_training/detection_for_smoke.pbtxt'
self.NUM_CLASSES = 1
self.detection_graph = self._load_model()
self.category_index = self._load_label_map()
def _load_model(self):
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(self.PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
return detection_graph
def _load_label_map(self):
label_map = label_map_util.load_labelmap(self.PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map,
max_num_classes=self.NUM_CLASSES,
use_display_name=True)
category_index = label_map_util.create_category_index(categories)
return category_index
def detect(self, image):
with self.detection_graph.as_default():
with tf.Session(graph=self.detection_graph) as sess:
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image, axis=0)
image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')
# Actual detection.
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
print(boxes, scores, classes, num_detections)
#print(np.squeeze(boxes))
# Visualization of the results of a detection.
#######Here is the problem
# image1 = vis_util.visualize_boxes_and_labels_on_image_array(
image, #######Here is the problem
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
self.category_index,
use_normalized_coordinates=True,
line_thickness=50,
)
#print(np.squeeze(boxes),np.squeeze(classes))
cv2.namedWindow("detection")
cv2.imshow("detection", image1)
cv2.waitKey(0)
if __name__ == '__main__':
image = cv2.imread('/home/xiyou/Pictures/timg1.jpg')
detecotr = TOD()
detecotr.detect(image)
when I run this code , the image did show ,but nothing changed , no detected area in the pic and no an other informations . the input pic is the same as the out image . But when I was Debug , I found the Varibles such as soucres , classes , boxes do have values.
Is anyone can help me ? Thanks!!!
And my Tensorflow version is 1.4.0 , CUDA 8.0 in Ubuntu 16.04
I am trying to display rich text (or html) in a segment of a wx python frame
I have tried the rtf control with no luck (see here). I am now trying the html route, but in the only examples I can find the html is display in a window that takes over the whole frame; for example from here
import wx
import wx.html
class MyHtmlFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title)
html = wx.html.HtmlWindow(self)
if "gtk2" in wx.PlatformInfo:
html.SetStandardFonts()
html.SetPage(
"Here is some <b>formatted</b> <i><u>text</u></i> "
"loaded from a <font color=\"red\">string</font>.")
app = wx.PySimpleApp()
frm = MyHtmlFrame(None, "Simple HTML")
frm.Show()
app.MainLoop()
Is it possible to display html in a textbox or some other suitable control that I can incorporate into my application?
I want the screen to look like that below. Can the wx.TextCtrl be replaced by an HTML window or something?
import wx
class MainFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title)
panel = MainPanel(self)
panel.txt_comments.SetValue(
"Here is some <b>formatted</b>"
"<i><u>text</u></i> "
"loaded from a "
"<font color=\"red\">string</font>.")
class MainPanel(wx.Panel):
def __init__(self, frame):
wx.Panel.__init__(self, frame)
txt_style = wx.VSCROLL|wx.HSCROLL|wx.TE_READONLY|wx.BORDER_SIMPLE
self.txt_comments = wx.TextCtrl(self, size=(300, 150), style=txt_style)
cmd_update = wx.Button(self, wx.ID_REFRESH)
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(self.txt_comments, flag=wx.ALL, border=10)
main_sizer.Add(cmd_update, flag=wx.ALL, border=10)
self.SetSizerAndFit(main_sizer)
app = wx.App()
frm = MainFrame(None, "Screen layout")
frm.Show()
app.MainLoop()
This must be somewhat close to an utter minimum of code.
#!/usr/bin/env python
import wx
import wx.html as html
#----------------------------------------------------------------------
ID_New = wx.NewId()
ID_Exit = wx.NewId()
#----------------------------------------------------------------------
class MyParentFrame(wx.MDIParentFrame):
def __init__(self):
wx.MDIParentFrame.__init__(self, None, -1, "MDI Parent", size=(600,400))
self.winCount = 0
menu = wx.Menu()
menu.Append(ID_New, "&New Window")
menu.AppendSeparator()
menu.Append(ID_Exit, "E&xit")
menubar = wx.MenuBar()
menubar.Append(menu, "&File")
self.SetMenuBar(menubar)
self.CreateStatusBar()
self.Bind(wx.EVT_MENU, self.OnNewWindow, id=ID_New)
self.Bind(wx.EVT_MENU, self.OnExit, id=ID_Exit)
def OnExit(self, evt):
self.Close(True)
def OnNewWindow(self, evt):
self.winCount = self.winCount + 1
win = wx.MDIChildFrame(self, -1, "Child Window: %d" % self.winCount)
self.html = html.HtmlWindow(win, -1)
self.html.SetPage(
"Here is some <b>formatted</b> <i><u>text</u></i> "
"loaded from a <font color=\"red\">string</font>.")
#----------------------------------------------------------------------
if __name__ == '__main__':
class MyApp(wx.App):
def OnInit(self):
frame = MyParentFrame()
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(False)
app.MainLoop()
I expect the main lines to note are these:
win = wx.MDIChildFrame(self, -1, "Child Window: %d" % self.winCount)
self.html = html.HtmlWindow(win, -1)
self.html.SetPage(
"Here is some <b>formatted</b> <i><u>text</u></i> "
"loaded from a <font color=\"red\">string</font>.")
win is the frame in which you want to house the HTMLWindow.
Notice that win is the first parameter to HTMLWindow.
I used wxWindow quite a bit several years ago, and I've lost most of my skills. Now I remember that the secret to getting a leg up is to start with the demo codes. I used a couple of them this time.
Edit on the basis of comments:
import wx
import wx.html as html
class MainFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title)
panel = MainPanel(self)
class MainPanel(wx.Panel):
def __init__(self, frame):
wx.Panel.__init__(self, frame)
txt_style = wx.VSCROLL|wx.HSCROLL|wx.TE_READONLY|wx.BORDER_SIMPLE
self.html = html.HtmlWindow(self, -1, size=(300, 150), style=txt_style)
self.html.SetPage(
"Here is some <b>formatted</b>"
"<i><u>text</u></i> "
"loaded from a "
"<font color=\"red\">string</font>.")
app = wx.App()
frm = MainFrame(None, "Screen layout")
frm.Show()
app.MainLoop()
wx.html.HtmlWindow or wx.html2.WebView are much like other child widgets in wxPython, in that they need a parent, and the size and position need to be managed in some way, and so on. That also means that you can replace the use of TextCtrl in your sample with one of those widgets, and replace SetValue with SetPage and it should work the way you want. See the docs for specifics and give it a try.