wxpython - Menu interaction - menu

I'm having trouble with a menu system - I have a basic example here (below) that shows a basic menu example I've followed; specifically, my issue is how may I make decisions from use menu choices, I'm not sure how to interact user choice with a menu choice?
Could someone point me in the right direction, or ideally give a brief example on this - say input data from a menu and display this?
Thanks
import wx
class myFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id,'Menu', size=(300,200))
panel = wx.Panel(self)
status = self.CreateStatusBar()
menubar = wx.MenuBar()
firstMenu = wx.Menu()
secondMenu = wx.Menu()
# create files
firstMenu.Append(wx.NewId(), 'Save Data' , 'Save data')
firstMenu.Append(wx.NewId(), 'Open Data..', 'Open a new window')
secondMenu.Append(wx.NewId(),'Configure..', 'Input Data here')
# append to menu
menubar.Append(firstMenu, 'File')
menubar.Append(secondMenu,'Options')
#
self.SetMenuBar(menubar)
if( __name__ == '__main__' ):
app = wx.PySimpleApp()
frame = myFrame(parent=None, id=-1)
frame.Show()
app.MainLoop()

You have to bind wx.EVT_MENU event. See wxPython demo for more examples. In your case that would be somethink like:
import wx
SAVE_DATA = wx.NewId()
OPEN_DATA = wx.NewId()
CONFIGURE = wx.NewId()
class myFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id,'Menu', size=(300,200))
panel = wx.Panel(self)
status = self.CreateStatusBar()
menubar = wx.MenuBar()
firstMenu = wx.Menu()
secondMenu = wx.Menu()
# create files
firstMenu.Append(SAVE_DATA, 'Save Data' , 'Save data')
firstMenu.Append(OPEN_DATA, 'Open Data..', 'Open a new window')
secondMenu.Append(CONFIGURE,'Configure..', 'Input Data here')
# append to menu
menubar.Append(firstMenu, 'File')
menubar.Append(secondMenu,'Options')
#
self.SetMenuBar(menubar)
self.Bind(wx.EVT_MENU, self.SaveData, id=SAVE_DATA)
self.Bind(wx.EVT_MENU, self.OpenData, id=OPEN_DATA)
self.Bind(wx.EVT_MENU, self.Configure, id=CONFIGURE)
def SaveData(self, e):
print("Save")
def OpenData(self, e):
print("Open")
def Configure(self, e):
print("Config")
if( __name__ == '__main__' ):
app = wx.PySimpleApp()
frame = myFrame(parent=None, id=-1)
frame.Show()
app.MainLoop()

Related

How can i load class in notebook when tab is clicked in wxpython?

Here i have a doubt that when notebook tab is clicked at that time only it should load class in that tab. But in wxpython all class loads by default in tab so how can i put conditions to load class when tab is clicked.
Here is a small example.
import wx
class tabclass(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
t = wx.StaticText(self, -1, "This is the help tab", (20,20))
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="notebook")
mainPanel = wx.Panel(self,size=(1365, 700), pos=(0, 71), style=wx.DOUBLE_BORDER)
self.nb = wx.Notebook(mainPanel,size=(1365, 700))
tab0 = tabclass(self.nb)
self.nb.AddPage(tab0, "Tab One")
if __name__ == "__main__":
app = wx.App()
MainFrame().Show()
app.MainLoop()
Here I want to display static text when the tab is clicked otherwise class should not load.
You might want a different method of selecting what is and what is not displayed in the notebook.
A menu, for example, seems an appropriate selection tool.
i.e.
import wx
class tabclass(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
t = wx.StaticText(self, -1, "This is the help tab", (20,20))
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="notebook")
mainPanel = wx.Panel(self,size=(1365, 700), pos=(0, 71), style=wx.DOUBLE_BORDER)
self.nb = wx.Notebook(mainPanel,size=(1365, 700))
tabmenu = wx.Menu()
t1 = wx.MenuItem(tabmenu, id = -1, text="Help", kind=wx.ITEM_CHECK)
tabmenu.Append(t1)
t2 = wx.MenuItem(tabmenu, id = -1, text="Other tab", kind=wx.ITEM_CHECK)
tabmenu.Append(t2)
t3 = wx.MenuItem(tabmenu, id = -1, text="Another tab", kind=wx.ITEM_CHECK)
tabmenu.Append(t3)
tabmenu.Append(wx.ID_EXIT, '&Quit')
# Creating the menubar.
menuBar = wx.MenuBar()
# Add menus
menuBar.Append(tabmenu, "&Tabs")
# Adding the MenuBar to the Frame content.
self.SetMenuBar(menuBar)
# Bind menu item to functions
self.Bind(wx.EVT_MENU, self.helptab, t1)
self.Bind(wx.EVT_MENU, self.othertab, t2)
self.Bind(wx.EVT_MENU, self.anothertab, t3)
self.Bind(wx.EVT_MENU, self.OnQuit, id=wx.ID_EXIT)
# Obviously, here you would differentiate your tabs
# I have used the same one for brevity
def helptab(self, event):
if event.IsChecked():
self.tab0 = tabclass(self.nb)
self.nb.AddPage(self.tab0, "Help Tab")
else:
#Delete the "Help Tab"
pass
def othertab(self, event):
if event.IsChecked():
self.tab1 = tabclass(self.nb)
self.nb.AddPage(self.tab1, "Other Tab")
else:
#Delete the "Other Tab"
pass
def anothertab(self, event):
if event.IsChecked():
self.tab2 = tabclass(self.nb)
self.nb.AddPage(self.tab2, "Another Tab")
else:
#Delete the "Another Tab"
pass
def OnQuit(self, event):
self.Destroy()
if __name__ == "__main__":
app = wx.App()
MainFrame().Show()
app.MainLoop()

How can I execute a child python scriptby clicking on a button on a parent script?

I am currently training OOP for GUI. I am using the wxPython library to create my windows and customize them.
Right now, I am trying to launch a python script by clicking on a button from an other script.
For that, I have 2 programs, wx_Practicing.py and wx_Practicing_child.py which are in the same folder.
wx_Practicing.py
import wx
import time
import wx_Practicing_child
import threading
import os
import sys
class MainWindow(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Test",
wx.DefaultPosition,(1000,850), wx.DEFAULT_FRAME_STYLE, wx.FrameNameStr)
# Click counter and flag variable for the new frame opened
self.click = 0
self.OpenButtonFlag = 0
# Sizer to definit the position of elements
sizer_hori = wx.BoxSizer(wx.HORIZONTAL)
sizer_verti = wx.BoxSizer(wx.VERTICAL)
# Panel
test_panel = PanelMainWindow(self)
test_panel.SetSizer(sizer_verti)
# Button to close the main frame and end the program
btn_quit = wx.Button(test_panel, label ="Quit")
btn_quit.Bind(wx.EVT_BUTTON, self.OnQuit)
sizer_verti.Add(btn_quit)
# Button which displays the number of click done on it since the
# frame is opened
btn_counter = wx.Button(test_panel, label="Click counter")
sizer_verti.Add(btn_counter)
btn_counter.Bind(wx.EVT_LEFT_DOWN, self.OnCount)
# Button which open the child frame from wx_Practicing_child.py
btn_new_frame = wx.Button(test_panel, label = "Open new frame")
sizer_verti.Add(btn_new_frame)
btn_new_frame.Bind(wx.EVT_LEFT_DOWN, self.OnNewFrame)
self.Show()
# Method to quit the frame and close it
def OnQuit(self, event):
self.Close()
#Method to count clicks
def OnCount(self, event):
self.click +=1
print(self.click)
# MEthod which open the child frame
def OnNewFrame(self, event):
if self.OpenButtonFlag == 0 :
print('aaaaaaaa')
os.system('wx_Practicing_child.py')
self.Show()
print("New frame opened")
self.OpenButtonFlag = 1
else :
print("Frame already launched, close it before opening a new one")
class PanelMainWindow(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
test = wx.App(False)
frame = MainWindow()
test.MainLoop()
wx_Practicing_child.py
import wx
class MainWindow_child(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Test",
wx.DefaultPosition, (1000,850), wx.DEFAULT_FRAME_STYLE, wx.FrameNameStr)
self.OpenButtonFlag = 0
# Sizer
sizer_hori = wx.BoxSizer(wx.HORIZONTAL)
sizer_verti = wx.BoxSizer(wx.VERTICAL)
# Panel
test_panel_child = PanelMainWindow_child(self)
test_panel_child.SetSizer(sizer_verti)
# Button to quit the child frame
btn_quit = wx.Button(test_panel_child, label ="Quit")
btn_quit.Bind(wx.EVT_BUTTON, self.OnQuit)
sizer_verti.Add(btn_quit)
self.Show()
# Method used to close the child frame
def OnQuit(self, event):
self.OpenButtonFlag = 0
self.Close()
class PanelMainWindow_child(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
So basically, the functionning is simple. I launch wx_Practicing.py to open the parent window, then I click on the "Open new frame" button and the child frame from wx_Practicing_child.py appears. If i trigger the button again, it does nothing until I closed the previous child window.
But when I try it, the buttonFlag is set to 1, so it enters in the loop, but the child frame does not appear.
So I would like to know how could I make it work. I am out of option right now.
Thank you.
Welcome to StackOverflow.
The problem is that you are creating the child frame in the wrong way.
You only need to change the line:
os.system('wx_Practicing_child.py')
for:
child = wx_Practicing_child.MainWindow_child()

how entrer value in new window and passing values of wx.newindow to wx.Frame wxpython

i have a panel with button Dynamic and when i click in button i have a new window opened the problem that i need zone to enter values to edit parameter of dynamic image like that :
that my code :
import wx
class MainFrame(wx.Frame):
def __init__(self,parent):
wx.Frame.__init__(self,parent,title="Myfirst",size=(800,580))
self.top = wx.Panel(self, style = wx.SUNKEN_BORDER)
self.bottom = wx.Panel(self ,style = wx.SUNKEN_BORDER)
self.left = wx.Panel(self ,style = wx.SUNKEN_BORDER, size = (250,-1))
st1 = wx.StaticText(self.bottom, -1, "show info ")
self.bottom.SetBackgroundColour('white')
dynamic=wx.Button(self.left,-1,"Dynamique",size=(110,30),pos=(50,100))
self.Bind(wx.EVT_BUTTON, self.newwindow, dynamic)
sizer1 = wx.BoxSizer(wx.VERTICAL)
sizer1.Add(self.top,1,wx.EXPAND,5)
sizer1.Add(self.bottom,1,wx.EXPAND,5)
sizer2 = wx.BoxSizer(wx.HORIZONTAL)
sizer2.Add(self.left,0,wx.EXPAND,5)
sizer2.Add(sizer1,1,wx.EXPAND,5)
self.SetSizer(sizer2)
def newwindow(self, event):
secondWindow = window2(parent=self.left)
secondWindow.Show()
class window2(wx.Frame):
title = "new Window"
def __init__(self,parent):
wx.Frame.__init__(self,parent, -1,'Dynamic of image', size=(300,100))
panel=wx.Panel(self, -1)
self.SetBackgroundColour(wx.Colour(100,100,100))
self.Centre()
self.Show()
app = wx.App()
frame=MainFrame(None).Show()
app.MainLoop()
how can i add the zone to edit parametre like picture ?
i not sure if the newwindow what i need or dialog !!
thanks for help
I guess you will be fine with a normal new window. You can get the zone to write the parameters with a wx.TextCtrl widgets. You will need a way to export the values typed into the wx.TextCtrl so I added the style wx.TE_PROCESS_ENTER. With this style when you finish typing and press Enter you can process the typed values.
Also, there is no need to use Show() two times (secondWindow.Show() and self.Show()). One of them is enough.
Code with comments:
import wx
class MainFrame(wx.Frame):
def __init__(self,parent):
wx.Frame.__init__(self,parent,title="Myfirst",size=(800,580))
self.top = wx.Panel(self, style = wx.SUNKEN_BORDER)
self.bottom = wx.Panel(self ,style = wx.SUNKEN_BORDER)
self.left = wx.Panel(self ,style = wx.SUNKEN_BORDER, size = (250,-1))
st1 = wx.StaticText(self.bottom, -1, "show info ")
self.bottom.SetBackgroundColour('white')
dynamic=wx.Button(self.left,-1,"Dynamique",size=(110,30),pos=(50,100))
self.Bind(wx.EVT_BUTTON, self.newwindow, dynamic)
sizer1 = wx.BoxSizer(wx.VERTICAL)
sizer1.Add(self.top,1,wx.EXPAND,5)
sizer1.Add(self.bottom,1,wx.EXPAND,5)
sizer2 = wx.BoxSizer(wx.HORIZONTAL)
sizer2.Add(self.left,0,wx.EXPAND,5)
sizer2.Add(sizer1,1,wx.EXPAND,5)
self.SetSizer(sizer2)
def newwindow(self, event):
secondWindow = window2(parent=self.left)
secondWindow.Show()
class window2(wx.Frame):
title = "new Window"
def __init__(self,parent):
"""
This is similar to the class MainFrame. You define a parent wx.Panel
and all other widgets are his childs.
"""
wx.Frame.__init__(self,parent, -1,'Dynamic of image', size=(300,100))
self.panel=wx.Panel(self, -1, style=wx.SUNKEN_BORDER)
self.st = wx.StaticText(self.panel, label='modifier bornes de la dynamique', style=wx.ALIGN_CENTER)
#### Notice the wx.TE_PROCESS_ENTER style to trigger processing the input when
#### Enter is pressed. Another alternative is to put a button somewhere.
self.text = wx.TextCtrl(self.panel, size=(200, 20), style=wx.SUNKEN_BORDER|wx.TE_PROCESS_ENTER)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.st, 0, wx.EXPAND|wx.ALL, 5)
self.sizer.Add(self.text, 0, wx.ALIGN_CENTER|wx.ALL, 5)
self.panel.SetSizer(self.sizer)
self.sizer.Fit(self.panel)
#self.SetBackgroundColour(wx.Colour(100,100,100))
self.Centre()
#### No need to use Show() here since you already use it in MainFrame.newwindow()
self.Show()
#### To execute self.onEnter when Enter is pressed inside self.text
self.Bind(wx.EVT_TEXT_ENTER, self.onEnter)
def onEnter(self, event):
#### Change it to fit your needs
print(self.text.GetValue())
self.Destroy()
app = wx.App()
frame=MainFrame(None).Show()
app.MainLoop()

trying to set functionality of menu items in menu bar with wxpython

here's my code for setting up the menu items in menu-bar with their functionally. but I don't know why but its just not working, I mean when I set open's functionally it worked but when I'm setting others it didn't and nor it is taking the history menu and help menu. presently I have commented the history and help code but when I remove the commas it gives error. (I'm not too good with python I have just started so need some help, in getting where I'm wrong.)
import wx
class MyApp(wx.App):
def OnInit(self):
self.frame = MenuFrame(None, title="Menus and MenuBars")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
ID_READ_ONLY = wx.NewId()
class MenuFrame(wx.Frame):
def __init__(self, *args, **kwargs):
super(MenuFrame, self).__init__(*args, **kwargs)
# Attributes
self.panel = wx.Panel(self)
self.txtctrl = wx.TextCtrl(self.panel,
style=wx.TE_MULTILINE)
# Layout
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.txtctrl, 1, wx.EXPAND)
self.panel.SetSizer(sizer)
self.CreateStatusBar() # For output display
# Setup the Menu
menub = wx.MenuBar()
# File Menu
filem = wx.Menu()
filem.Append(wx.ID_NEW, "New\tCtrl+N")
filem.Append(wx.ID_OPEN, "Open\tCtrl+O")
filem.Append(wx.ID_SAVE, "Save\tCtrl+S")
filem.Append(wx.ID_SAVEAS, "Save_As\tCtrl+Shift+S")
menub.Append(filem, "&File")
# Edit Menu
editm = wx.Menu()
editm.Append(wx.ID_UNDO, "Undo\tCtrl+Z")
editm.Append(wx.ID_REDO, "Redo\tCtrl+Shift+Z")
editm.Append(wx.ID_COPY, "Copy\tCtrl+C")
editm.Append(wx.ID_CUT, "Cut\tCtrl+X")
editm.Append(wx.ID_PASTE, "Paste\tCtrl+V")
editm.Append(wx.ID_SELECTALL, "SelectAll\tCtrl+A")
editm.AppendSeparator()
editm.Append(ID_READ_ONLY, "Read Only",
kind=wx.ITEM_CHECK)
menub.Append(editm, "E&dit")
"""# History Menu
historym = wx.Menu()
historym.Append(wx.ID_RECENT, "Recent\tCtrl+N")
menub.Append(historym, "&History")
# Help Menu
helpm = wx.Menu()
helpm.Append(wx.ID_HINT, "Hint")
helpm.Append(wx.ID_ABOUT, "About")
menub.Append(helpm, "&Help")"""
self.SetMenuBar(menub)
# Event Handlers
self.Bind(wx.EVT_MENU, self.OnMenu)
def OnMenu(self, event):
"""Handle menu clicks"""
evt_id = event.GetId()
actions = { wx.ID_COPY : self.txtctrl.Copy,
wx.ID_CUT : self.txtctrl.Cut,
wx.ID_PASTE : self.txtctrl.Paste }
action = actions.get(evt_id, None)
if action:
action()
elif evt_id == ID_READ_ONLY:
# Toggle enabled state
self.txtctrl.Enable(not self.txtctrl.Enabled)
elif evt_id == wx.ID_OPEN:
dlg = wx.FileDialog(self, "Open File", style=wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
fname = dlg.GetPath()
handle = open(fname, 'r')
self.txtctrl.SetValue(handle.read())
handle.close()
else:
event.Skip()
if __name__ == "__main__":
app = MyApp(False)
app.MainLoop()
The problem with the history and help menus, is that the Id's that you are using do not exist i.e. ID_RECENT and ID_HINT, so use something else or assign your own Id's.
The selectall function was not assigned.
Note, that the cut and copy functions require that you have selected something.
You haven't written any code for the Save or Saveas functions.
The undo and redo functions do not seem to function in a standard wx.TextCtrl, so you could use a StyledTextCtrl instead.
Hopefully, the code below will move you on a bit.
(It's for wxpython Phoenix and python3 on Linux)
import wx
import wx.stc
class MyApp(wx.App):
def OnInit(self):
self.frame = MenuFrame(None, title="Menus and MenuBars")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
ID_READ_ONLY = wx.NewId()
class MenuFrame(wx.Frame):
def __init__(self, *args, **kwargs):
super(MenuFrame, self).__init__(*args, **kwargs)
# Attributes
self.panel = wx.Panel(self)
self.txtctrl = wx.stc.StyledTextCtrl(self.panel,
style=wx.TE_MULTILINE)
# Layout
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.txtctrl, 1, wx.EXPAND)
self.panel.SetSizer(sizer)
self.CreateStatusBar() # For output display
# Setup the Menu
menub = wx.MenuBar()
# File Menu
filem = wx.Menu()
filem.Append(wx.ID_NEW, "New\tCtrl+N")
filem.Append(wx.ID_OPEN, "Open\tCtrl+O")
filem.Append(wx.ID_SAVE, "Save\tCtrl+S")
filem.Append(wx.ID_SAVEAS, "Save_As\tCtrl+Shift+S")
menub.Append(filem, "&File")
# Edit Menu
editm = wx.Menu()
editm.Append(wx.ID_UNDO, "Undo\tCtrl+Z")
editm.Append(wx.ID_REDO, "Redo\tCtrl+Shift+Z")
editm.Append(wx.ID_COPY, "Copy\tCtrl+C")
editm.Append(wx.ID_CUT, "Cut\tCtrl+X")
editm.Append(wx.ID_PASTE, "Paste\tCtrl+V")
editm.Append(wx.ID_SELECTALL, "SelectAll\tCtrl+A")
editm.AppendSeparator()
editm.Append(ID_READ_ONLY, "Read Only",
kind=wx.ITEM_CHECK)
menub.Append(editm, "E&dit")
# History Menu
historym = wx.Menu()
historym.Append(wx.ID_PREVIEW, "Recent\tCtrl+N")
menub.Append(historym, "&History")
# Help Menu
helpm = wx.Menu()
helpm.Append(wx.ID_HELP_INDEX, "Hint")
helpm.Append(wx.ID_ABOUT, "About")
menub.Append(helpm, "&Help")
self.SetMenuBar(menub)
# Event Handlers
self.Bind(wx.EVT_MENU, self.OnMenu)
def OnMenu(self, event):
"""Handle menu clicks"""
evt_id = event.GetId()
actions = { wx.ID_COPY : self.txtctrl.Copy,
wx.ID_CUT : self.txtctrl.Cut,
wx.ID_PASTE : self.txtctrl.Paste,
wx.ID_UNDO : self.txtctrl.Undo,
wx.ID_REDO : self.txtctrl.Redo,
wx.ID_SELECTALL : self.txtctrl.SelectAll}
action = actions.get(evt_id, None)
if action:
action()
elif evt_id == ID_READ_ONLY:
# Toggle enabled state
self.txtctrl.Enable(not self.txtctrl.Enabled)
elif evt_id == wx.ID_OPEN:
dlg = wx.FileDialog(self, "Open File", style=wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
fname = dlg.GetPath()
handle = open(fname, 'r')
self.txtctrl.SetValue(handle.read())
handle.close()
else:
event.Skip()
if __name__ == "__main__":
app = MyApp(False)
app.MainLoop()

wxpython run when textctrl changes

I am making a simple text editor in wxpython. I would like it to be able to edit code such as python, and as such I would like to have it highlight the text in a similar manner to IDLE or Notepad++. I know how I would highlight it, but I would like the best way of running it. I don't know if it is possible but what I would really like is to run whenever a key is pressed, and not on a loop checking if it is pressed, so as to save on processing.
import wx
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(500,600))
style = wx.TE_MULTILINE|wx.BORDER_SUNKEN|wx.TE_RICH2
self.status_area = wx.TextCtrl(self, -1,
pos=(10, 270),style=style,
size=(380,150))
self.status_area.AppendText("Type in your wonderfull code here.")
fg = wx.Colour(200,80,100)
at = wx.TextAttr(fg)
self.status_area.SetStyle(3, 5, at)
self.CreateStatusBar() # A Statusbar in the bottom of the window
# Setting up the menu.
filemenu= wx.Menu()
filemenu.Append(wx.ID_ABOUT, "&About","Use to edit python code")
filemenu.AppendSeparator()
filemenu.Append(wx.ID_EXIT,"&Exit"," Terminate the program")
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
self.Show(True)
app = wx.App(False)
frame = MainWindow(None, "Python Coder")
app.MainLoop()
If a loop is needed what would be the best way to make it loop, with a while loop, or a
def Loop():
<code>
Loop()
My new code with the added bind:
import wx
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(500,600))
style = wx.TE_MULTILINE|wx.BORDER_SUNKEN|wx.TE_RICH2
self.status_area = wx.TextCtrl(self, -1,
pos=(10, 270),style=style,
size=(380,150))
#settup the syntax highlighting to run on a key press
self.Bind(wx.EVT_CHAR, self.onKeyPress, self.status_area)
self.status_area.AppendText("Type in your wonderfull code here.")
fg = wx.Colour(200,80,100)
at = wx.TextAttr(fg)
self.status_area.SetStyle(3, 5, at)
self.CreateStatusBar() # A Statusbar in the bottom of the window
# Setting up the menu.
filemenu= wx.Menu()
filemenu.Append(wx.ID_ABOUT, "&About","Use to edit python code")
filemenu.AppendSeparator()
filemenu.Append(wx.ID_EXIT,"&Exit"," Terminate the program")
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
self.Show(True)
def onKeyPress (self, event):
print "KEY PRESSED"
kc = event.GetKeyCode()
if kc == WXK_SPACE or kc == WXK_RETURN:
Line = self.status_area.GetValue()
print Line
app = wx.App(False)
frame = MainWindow(None, "Python Coder")
app.MainLoop()
In your MainWindow __init__ function add this
self.Bind(wx.EVT_CHAR, self.onKeyPress, self.status_area)
then define onKeyPress in MainWindow
def onKeyPress (self, event):
kc = event.GetKeyCode()
if kc == WXK_SPACE or kc == WXK_RETURN:
#Run your highlighting code here
Come to think of it, this might not be the most efficient way of doing code highlighting. Let me look this up. But in the meantime you can try this.
Edit:
Take a look at this - StyledTextCtrl . I think its more along the lines of what you need.
I solved this when I faced the same issue by creating a custom event.
First, I created a subclass of the TextCtrl, so I had a place in code to raise/post the custom event from:
import wx.lib.newevent
(OnChangeEvent, EVT_VALUE_CHANGED) = wx.lib.newevent.NewEvent()
class TextBox(wx.TextCtrl):
old_value = u''
def __init__(self,*args,**kwargs):
wx.TextCtrl.__init__(self,*args,**kwargs)
self.Bind(wx.EVT_SET_FOCUS, self.gotFocus) # used to set old value
self.Bind(wx.EVT_KILL_FOCUS, self.lostFocus) # used to get new value
def gotFocus(self, evt):
evt.Skip()
self.old_value = self.GetValue()
def lostFocus(self, evt):
evt.Skip()
if self.GetValue() != self.old_value:
evt = OnChangeEvent(oldValue=self.old_value, newValue=self.GetValue())
wx.PostEvent(self, evt)
Now, in my frame's code, here is a snippet of me Binding the event, and using it.
summ_text_ctrl = TextBox(self, -1, size=(400, -1))
summ_text_ctrl.Bind(EVT_VALUE_CHANGED, self.onTextChanged)
def OnTextChanged(self, evt):
evt.Skip()
print('old Value: %s' % evt.oldValue )
print('new Value: %s' % evt.newValue )

Resources