Works on Fedora but not on Windows, wx.Phyton - events

Well im quite a noob with wx and i started learning it 5 days ago. I'm trying to make a game like memory with cards like bitmap buttons but events don't want to bind on my cards. I searched the Internet and asked some people for help but they don't know why. I sent the program to one person who works in Linux Fedora and he says it works...
The problem is in class MyDialog, function Cards. I made a test program, similar to this one and binded the events in the for command where it worked properly.
Sorry if the answer exists somewhere on this website, I couldn't find it...
import random
import wx
global n
global ControlVar
ControlVar = False
class MyDialog(wx.Dialog):
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size=(200, 150))
wx.StaticBox(self, -1, 'Card pairs', (5, 5), size=(180, 70))
wx.StaticText(self, -1, 'Number: ', (15, 40))
self.spin = wx.SpinCtrl(self, -1, '1', (65, 40), (60, -1), min=3, max=5)
self.spin.SetValue(4)
wx.Button(self, 2, 'Ok', (70, 85), (60, -1))
self.Bind(wx.EVT_BUTTON, self.OnClose, id=2)
self.Centre()
self.ShowModal()
self.Destroy()
def OnClose(self, event):
pair = self.spin.GetValue()
self.Close()
return(pair)
class MyMenu(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(1000, 700))
self.SetMinSize(wx.Size(400, 300))
self.panel = wx.Panel(self, wx.ID_ANY)
self.SetIcon(wx.Icon('computer.png', wx.BITMAP_TYPE_ANY))
bmp = wx.Image('wood.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap()
bitmap = wx.StaticBitmap(self, -1, bmp, (0, 0))
menubar = wx.MenuBar()
file = wx.Menu()
edit = wx.Menu()
file.Append(101, '&New Game', 'Start a New Game')
file.AppendSeparator()
file.Append(105,'&Quit\tEsc', 'Quit the Application')
menubar.Append(file, '&File')
self.SetMenuBar(menubar)
self.statusbar = self.CreateStatusBar()
self.Centre()
self.Bind(wx.EVT_MENU, self.OnNew, id=101)
self.Bind(wx.EVT_MENU, self.OnQuit, id=105)
self.panel.Bind(wx.EVT_KEY_DOWN, self.OnKey)
def OnNew(self, event):
if ControlVar:
for i in range(n*2):
self.dugmad[i].Destroy()
md = MyDialog(None, -1, 'New Game')
n = md.OnClose(None)
self.statusbar.SetStatusText('You Selected {} Pairs.'.format(n))
self.Cards()
def OnButton(self, event):
print('ANYTHING PLEASE!')
## problem ahead!
def Cards(self):
image = wx.Image('cveteki.jpg', wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.dugmad = []
for i in range(2*n):
dugme = wx.BitmapButton(self, i, image)
self.dugmad.append(dugme)
self.Bind(wx.EVT_BUTTON, self.OnButton, id=i)
if n == 3:
self.Draw(2, 3)
if n == 4:
self.Draw(2, 4)
if n == 5:
self.Draw(2, 5)
def Draw(self,a, b):
gs = wx.GridSizer(a,b,40,40)
for i in range(n*2):
gs.Add(self.dugmad[i],0, wx.EXPAND)
vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(gs, 1, wx.EXPAND | wx.ALL, 40)
self.SetSizer(vbox)
self.Layout()
self.Refresh()
global ControlVar
ControlVar=True
def OnKey(self, event):
keycode = event.GetKeyCode()
if keycode == wx.WXK_ESCAPE:
box = wx.MessageDialog(None, 'Are you sure you want to quit?', 'Quit', wx.YES_NO | wx.ICON_QUESTION)
if box.ShowModal() == wx.ID_YES:
self.Close()
def OnQuit(self, event):
box = wx.MessageDialog(None, 'Are you sure you want to quit?', 'Quit', wx.YES_NO | wx.ICON_QUESTION)
if box.ShowModal() == wx.ID_YES:
self.Destroy()
class MyApp(wx.App):
def OnInit(self):
frame = MyMenu(None, -1, 'Memory')
frame.Show(True)
return (True)
def main():
app = MyApp(False)
app.MainLoop()
main()

I tried to run your code but I don't have images with those names at the ready, and I can't understand all your globals, and I get an error about n not defined. So I made a simple test for you which I hope helps:
import wx
app = wx.App()
def onButton(evt):
print "button pressed!", evt.GetEventObject().GetLabel()
frm = wx.Frame(None)
for i in range(10):
but = wx.Button(frm, pos=(10, i*20), label="button %s" % i)
but.Bind(wx.EVT_BUTTON, onButton)
frm.Show()
app.MainLoop()
The but.Bind(...) could also be frm.Bind(...) if you really want. Note that I don't futz with the id's: I couldn't care less what id's wxPython assigned the buttons.
I'm not sure what's wrong with your code because I couldn't run it and didn't want to debug the other errors with it.
Again, I hope this helps.

But why are you destroying your MyDialog just after it is created? Check: there is self.Destroy() method call immediately after self.ShowModal().

Related

wxpython's treectrl can't expand in windows

Why my wxpython's treectrl can't show and expand in windows but ok in mac:
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(450, 350))
hbox = wx.BoxSizer(wx.HORIZONTAL)
vbox = wx.BoxSizer(wx.VERTICAL)
panel1 = wx.Panel(self, -1)
panel2 = wx.Panel(self, -1)
self.tree = wx.TreeCtrl(panel1, 1, wx.DefaultPosition, (-1,-1), wx.TR_HIDE_ROOT|wx.TR_HAS_BUTTONS)
root = self.tree.AddRoot('Programmer')
os = self.tree.AppendItem(root, 'Operating Systems')
self.tree.AppendItem(os, 'Linux')
self.tree.AppendItem(os, 'FreeBSD')
self.tree.AppendItem(os, 'OpenBSD')
self.tree.AppendItem(os, 'NetBSD')
self.tree.AppendItem(os, 'Solaris')
self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, id=1)
self.display = wx.StaticText(panel2, -1, '',(10,10), style=wx.ALIGN_CENTRE)
self.tree.Bind(wx.EVT_TREE_ITEM_EXPANDING,self.OnExpanding, id=1)
self.tree.Bind(wx.EVT_TREE_ITEM_EXPANDED,self.OnExpanded, id=1)
self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED,self.OnActivated, id=1)
self.tree.Bind(wx.EVT_TREE_ITEM_COLLAPSED,self.OnCollapsed, id=1)
self.tree.Bind(wx.EVT_TREE_ITEM_COLLAPSING,self.OnCollaping, id=1)
vbox.Add(self.tree, 1, wx.EXPAND)
hbox.Add(panel1, 1, wx.EXPAND)
hbox.Add(panel2, 1, wx.EXPAND)
panel1.SetSizer(vbox)
self.SetSizer(hbox)
self.Centre()
def OnSelChanged(self, event):
item = event.GetItem()
self.display.SetLabel(self.tree.GetItemText(item))
def OnExpanding(self,evt):
print "OnExpanding"
def OnExpanded(self,evt):
print "OnExpaned"
def OnActivated(self,evt):
print "OnActivated"
def OnCollapsed(self,evn):
print "OnCollapsed"
def OnCollaping(self,evt):
print "OnCollaping"
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'treectrl.py')
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
I run this code with:
python2.7-win32
wxPython3.0-win32-3.0.2.0-py27
window7-64
and in windows then event about expand and collaps is never be sended too
so how can tell me where am i wrong?
Apparently wx.TR_LINES_AT_ROOT is needed on Windows when hiding the root and you still want to display the expand/collapse buttons. Alternatively, you can just add the hide-root style to the default style and not have to worry about this platform specific difference, like: wx.TR_HIDE_ROOT | wx.TR_DEFAULT_STYLE

wxpython, how to set background color and foreground color in textctrl?

I want to set color for words, background and foreground colors both are needed. I learned tkinter first, but it seems wxpython have no similar methods.
the following code is easy to test, copy "hello world, Hello World, heLLo WORLD" to area_example, tell me how to highlight "hello", ignorecase
#!/usr/bin/env python
# coding=utf8
import wx
rows = 5
cols = 2
vgap = 20
hgap = 10
class Search(wx.Frame):
#not_resizable = wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) # ok
not_resizable = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)
def __init__(self, parent, title, size):
super(Search, self).__init__(parent, title=title, size=size, style=self.not_resizable)
self.init_elements()
self.lay_out()
self.Centre()
self.Show()
def init_elements(self):
self.panel = wx.Panel(self)
self.entry_name = wx.TextCtrl(self.panel)
self.entry_name.SetFocus()
self.btn_add = wx.Button(self.panel, label="Add")
self.btn_add.Disable()
self.btn_recite = wx.Button(self.panel, label="Recite")
self.btn_recite.Disable()
self.btn_flash = wx.Button(self.panel, label="Flash")
self.btn_flash.Disable()
self.label_phonetic = wx.StaticText(self.panel, label='')
self.area_meaning = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE)
self.area_example = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE)
self.btn_save = wx.Button(self.panel, label="Save")
self.btn_sort = wx.Button(self.panel, label="Sort")
def lay_out(self):
hbox = wx.BoxSizer(wx.HORIZONTAL)
grid = wx.FlexGridSizer(rows, cols, vgap, hgap)
grid.AddMany([
(self.entry_name), (self.btn_add),
(self.label_phonetic), (self.btn_recite),
(self.area_meaning, 1, wx.EXPAND), (self.btn_flash),
(self.area_example, 1, wx.EXPAND), (self.btn_sort),
(self.btn_save),
])
grid.AddGrowableCol(0, 1)
grid.AddGrowableRow(2, 1)
grid.AddGrowableRow(3, 1)
hbox.Add(grid, proportion=1, flag=wx.ALL | wx.EXPAND, border=15)
self.panel.SetSizer(hbox)
#self.panel.SetSizerAndFit(hbox)
def OnKeyUp(self, e):
code = e.GetKeyCode()
if code == wx.WXK_RETURN:
self.enter_handler(e)
def enter_handler(self, e):
word = self.entry_name.GetValue()
if word:
self.highlight(word)
def highlight(self, name):
# todo
# add background color and foreground color, ignore case
print 'highlight'
def search_test():
app = wx.App()
title = 'Search Test'
size = (800, 500)
s = Search(None, title, size)
s.entry_name.Bind(wx.EVT_KEY_UP, s.OnKeyUp)
app.MainLoop()
if __name__ == '__main__':
search_test()
the doc version when I asked the question was wxPython 3.0.3, last updated 13 March 2015 from revision 1725+2c3b7a8.
but the wxPython version brew install on osx was 3.0.2, some classes and methods were not available.
On the docs it explains how to do this: http://wxpython.org/Phoenix/docs/html/TextCtrl.html#phoenix-title-textctrl-styles
Here is an example snippet (Should go below your definition of self.area_example)
self.area_example.SetDefaultStyle(wx.TextAttr(wx.RED))
self.area_example.AppendText("Red text\n")
self.area_example.SetDefaultStyle(wx.TextAttr(wx.NullColour,
wx.LIGHT_GREY))
self.area_example.AppendText("Red on grey text\n")
self.area_example.SetDefaultStyle(wx.TextAttr(wx.BLUE))
self.area_example.AppendText("Blue on grey text\n")
As for checking if the word is "hello", I can only think right now as to bind it and check it.
self.area_example.Bind(wx.EVT_CHAR, self.OnKeyDown)
The "OnKeyDown" function is just an example. It runs but you'll most likely want a better way of doing it.
def OnKeyDown(self, e):
last_word = self.area_example.GetValue().split()[-1]
if last_word.lower() == "hello":
print("Change color")
e.Skip()
From there you should be able to accomplish what you need.

wxPython: Getting a EVT_KEY_DOWN event for CMD+[other key] on OSX

I'm trying to catch an event when the user presses COMMAND + [any other key] on OSX. Since these are actually two key presses I expect two events: One when COMMAND is pressed and one when the other key is pressed (without releasing the COMMAND key). This works fine for every modifier except COMMAND where I only get the first event. Why is that and how can I fix it?
Version: wxPython3.0-osx-cocoa-py2.7
Example code:
import wx
def OnKeyDown(e):
print "Modifiers: {} Key Code: {}".format(e.GetModifiers(), e.GetKeyCode())
app = wx.App()
frame = wx.Frame(None)
textctrl = wx.TextCtrl(frame, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, wx.WANTS_CHARS)
textctrl.Bind(wx.EVT_KEY_DOWN, OnKeyDown)
frame.Show()
app.MainLoop()
For ALT + d the output is:
Modifiers: 1 Key Code: 307
Modifiers: 1 Key Code: 68
For SHIFT + d the output is:
Modifiers: 4 Key Code: 306
Modifiers: 4 Key Code: 68
Only for COMMAND + d the output is:
Modifiers: 2 Key Code: 308
Thanks for your help
Additional Information: I'm using OSX 10.8 on a virtual machine. As RobinDunn points out that it works on his laptop. So chances are that this is just a problem in my environment. wnnmaw provided a good workaround which works for me even on the virtual environment.
Alright, so it took me some time, but here's a working code block that does what you want.
Some Things to Note:
I did this on Windows (so there are some changes you can make such as adding support for wx.ACCEL_RAW_CTRL which corresponds to the actual control key on Mac whereas wx.ACCCEL_CTRL corresponds to the command key
This code definitely can (and needs to be) cleaned up
You'll have to add better error checking before you give this to a user
Whithout further adieu, here it is
import wx
from wx.lib.scrolledpanel import ScrolledPanel
class TestWindow(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Accelerator Table Test', size=(600, 400))
self.panel = ScrolledPanel(parent=self, id=-1)
self.panel.SetupScrolling()
#Create IDs to be used in initial acclerator table
self.functionList = [self.func1, self.func2, self.func3, self.func4, self.func5, self.OnAdd, self.OnDel]
self.functionListstr = ["self.func1", "self.func2", "self.func3", "self.func4", "self.func5", "self.OnAdd", "self.OnDel"]
self.IDDict = {i: wx.NewId() for i in range(len(self.functionList))}
self.IDDictrev = {val:key for key, val in self.IDDict.iteritems()}
self.aTableList = [(wx.ACCEL_ALT, ord('S'), self.IDDict[0]),(wx.ACCEL_CTRL, ord('Q'), self.IDDict[1])]
#Set up initial accelerator table
aTable = wx.AcceleratorTable(self.aTableList)
self.SetAcceleratorTable(aTable)
#Bind inital accelerator table IDs to functions
for i in range(len(self.functionList)):
self.Bind(wx.EVT_MENU, self.functionList[i], id=self.IDDict[i])
#Set up control widgets on GUI
self.flexgrid = wx.FlexGridSizer(cols=3, hgap=10, vgap=5)
cmdkeylbl = wx.StaticText(self.panel, -1, "Command Key")
self.cmdkey = wx.ComboBox(self.panel, style=wx.CB_READONLY)
cmdkeylist = ["Alt", "Control/Command", "Shift", "OSX Control", "None"]
self.cmdkeyconstants = {"Alt":wx.ACCEL_ALT, "Control/Command":wx.ACCEL_CTRL, "Shift":wx.ACCEL_SHIFT, "None":wx.ACCEL_NORMAL}
self.cmdkeyconstantsrev = {val:key for key, val in self.cmdkeyconstants.iteritems()}
self.cmdkey.SetItems(cmdkeylist)
hotkeylbl = wx.StaticText(self.panel, -1, "HotKey (single letter only)")
self.hotkey = wx.TextCtrl(self.panel, size=(50,-1))
funclbl = wx.StaticText(self.panel, -1, "Function")
self.func = wx.ComboBox(self.panel, style=wx.CB_READONLY)
self.func.SetItems(self.functionListstr)
self.hbox = wx.BoxSizer(wx.HORIZONTAL)
addBtn = wx.Button(self.panel, -1, "Add")
delBtn = wx.Button(self.panel, -1, "Delete")
self.Bind(wx.EVT_BUTTON, self.OnAdd, addBtn)
self.Bind(wx.EVT_BUTTON, self.OnDel, delBtn)
self.vbox = wx.BoxSizer(wx.VERTICAL)
self.curATable = wx.StaticText(self.panel, -1, self._DisplayATable())
self.flexgrid.Add(cmdkeylbl)
self.flexgrid.Add(hotkeylbl)
self.flexgrid.Add(funclbl)
self.flexgrid.Add(self.cmdkey)
self.flexgrid.Add(self.hotkey)
self.flexgrid.Add(self.func)
self.hbox.Add((20, 20), 0)
self.hbox.Add(addBtn)
self.hbox.Add((0, 0), 0)
self.hbox.Add(delBtn)
self.hbox.Add((20, 20), 0)
self.vbox.Add(self.flexgrid, flag=wx.TOP|wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, border = 5)
self.vbox.Add(self.hbox, flag=wx.TOP|wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, border = 5)
self.vbox.Add(self.curATable, flag=wx.TOP|wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, border = 5)
self.panel.SetSizer(self.vbox)
self.panel.Layout()
#Class Functions
def _DisplayATable(self):
aTablelbl = ""
for cmdKey, hotKey, Func in self.aTableList:
aTablelbl += "{} + {} calls {}\n".format(self.cmdkeyconstantsrev[cmdKey], chr(hotKey), self.functionListstr[self.IDDictrev[Func]])
return aTablelbl
def OnAdd(self, event):
self.aTableList.append((self.cmdkeyconstants[self.cmdkey.GetValue()], ord(self.hotkey.GetValue()[:1].title()), self.IDDict[self.func.GetSelection()]))
print "Added {} + {} as a shortcut for {}!".format(self.cmdkey.GetValue(), self.hotkey.GetValue()[:1].title(), self.functionListstr[self.func.GetSelection()])
aTable = wx.AcceleratorTable(self.aTableList)
self.SetAcceleratorTable(aTable)
self.curATable.SetLabel(self._DisplayATable())
self.panel.Layout()
def OnDel(self, event):
if (self.cmdkeyconstants[self.cmdkey.GetValue()], ord(self.hotkey.GetValue()[:1].title()), self.IDDict[self.func.GetSelection()]) in self.aTableList:
self.aTableList.remove((self.cmdkeyconstants[self.cmdkey.GetValue()], ord(self.hotkey.GetValue()[:1].title()), self.IDDict[self.func.GetSelection()]))
aTable = wx.AcceleratorTable(self.aTableList)
self.SetAcceleratorTable(aTable)
self.curATable.SetLabel(self._DisplayATable())
self.panel.Layout()
else:
dlg = wx.MessageDialog(self, "ERROR: That combination is not in the accelerator table!", "Error", style=wx.OK)
dlg.ShowModal()
dlg.Destroy()
def func1(self, event):
dlg = wx.MessageDialog(self, "Func1", "Func1", style=wx.OK)
dlg.ShowModal()
dlg.Destroy()
def func2(self, event):
dlg = wx.MessageDialog(self, "Func2", "Func2", style=wx.OK)
dlg.ShowModal()
dlg.Destroy()
def func3(self, event):
dlg = wx.MessageDialog(self, "Func3", "Func3", style=wx.OK)
dlg.ShowModal()
dlg.Destroy()
def func4(self, event):
dlg = wx.MessageDialog(self, "Func4", "Func4", style=wx.OK)
dlg.ShowModal()
dlg.Destroy()
def func5(self, event):
dlg = wx.MessageDialog(self, "Func5", "Func5", style=wx.OK)
dlg.ShowModal()
dlg.Destroy()
app = wx.App(False)
frame = TestWindow()
frame.Show()
app.MainLoop()
Hopefully this is what you're looking for, let me know if you have any questions

How to smooth redrawing objects on the form (wxPython)

I'm writing simple GUI using wxPyhon and faced some problems.
My application does simple things: it draws triangle on the form and rotates it when user clicks arrow buttons or drags a mouse cursor over the form.
THe problems I see now are following:
1. Then I drag a mouse sursor fast the triangle rotates with keeping old image visible for a short time. When keeping moving a cursor fast for a while the drawing on the form is looking like 2 or 3 triangles.
2. If I expand the form to entire size of the screen the triangle moves unsmoothly, with small jumps from old appearance to a new one. I looked at coordinates of a mouse cursor during that rotating and noticed that they are tracked with gaps. Friend of mine said me that it is because I redraw the entire window of the application every time I wand to rotate the triangle a little bit. And that's why it works slowly and it slow down the tracking of a mouse cursor.
To refresh the view I'm using wx.Panel.Refresh() method. As drawing context I'm using wx.BufferedDC()
Please tell me how to draw CORRECTLY dynamicaly changing pictures/drawings on the wxPython forms, especially the way I make in that application.
I could place my code here, but it's too long. So if I must tell something more about my case - ask me please, I will answer.
Thanks !
class SimpleGraphics(wx.Panel):
def __init__(self, parent, size=(50, 50)):
super(SimpleGraphics, self).__init__(parent,
size=size,
style=wx.NO_BORDER)
self.color = "Black"
self.thickness = 2
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
self.MARGIN = 1 #px
self.points = [[0.0, 0.5], [0.5, 0.0], [-0.5, -0.5]]
self.pos = (0, 0)
self.cur_vector = Vector2D(1, 1)
self.InitBuffer()
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_IDLE, self.OnIdle)
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyArrow)
# MOUSE TRACKING
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
self.Bind(wx.EVT_MOTION, self.OnMotion)
self.Bind(wx.EVT_PAINT, self.OnPaint)
def InitBuffer(self):
self.client_size = self.GetClientSize()
self.buffer = wx.EmptyBitmap(self.client_size.width, self.client_size.height)
dc = wx.BufferedDC(None, self.buffer)
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
self.DrawImage(dc)
self.reInitBuffer = False
def OnSize(self, event):
self.reInitBuffer = True
def repaint_the_view(self):
self.InitBuffer()
self.Refresh()
def OnIdle(self, event):
if self.reInitBuffer:
self.repaint_the_view()
def OnKeyArrow(self, event):
key_code = event.GetKeyCode()
if key_code == wx.WXK_LEFT:
self.rotate_points(degrees_to_rad(5))
elif key_code == wx.WXK_RIGHT:
self.rotate_points(degrees_to_rad(-5))
self.repaint_the_view()
event.Skip()
def OnLeftDown(self, event):
# get the mouse position and capture the mouse
self.pos = event.GetPositionTuple()
self.cur_vector = create_vector2d(self.pos[0], self.pos[1],
self.client_size.width / 2,
self.client_size.height / 2)
self.CaptureMouse()
def OnLeftUp(self, event):
#release the mouse
if self.HasCapture():
self.ReleaseMouse()
def OnMotion(self, event):
if event.Dragging() and event.LeftIsDown():
newPos = event.GetPositionTuple()
new_vector = create_vector2d(newPos[0], newPos[1],
self.client_size.width / 2,
self.client_size.height / 2)
if new_vector.lenth() > 0.00001:
c = cos_a(self.cur_vector, new_vector)
s = sin_a(self.cur_vector, new_vector)
rot_matr = rotation_matrix(s, c)
self.rotate_points(rot_matr=rot_matr)
dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) # this line I've added after posting the question
self.repaint_the_view()
self.cur_vector = new_vector
event.Skip()
def OnPaint(self, event):
wx.BufferedPaintDC(self, self.buffer)
def DrawImage(self, dc):
dc.SetPen(self.pen)
new_points = self.convetr_points_to_virtual()
dc.DrawPolygon([wx.Point(x, y) for (x, y) in new_points])
def to_x(self, X_Log):
X_Window = self.MARGIN + (1.0 / 2) * (X_Log + 1) * (self.client_size.width - 2 * self.MARGIN)
return int(X_Window)
def to_y(self, Y_Log):
Y_Window = self.MARGIN + (-1.0 / 2) * (Y_Log - 1) * (self.client_size.height - 2 * self.MARGIN)
return int(Y_Window)
def convetr_points_to_virtual(self):
return [(self.to_x(x), self.to_y(y)) for (x, y) in self.points]
def rotate_points(self, angle_in_degrees=None, rot_matr=None):
if angle_in_degrees is None:
self.points = [rotate_point(x, y , rotator_matrix=rot_matr) for (x, y) in self.points]
else:
self.points = [rotate_point(x, y , angle_in_degrees) for (x, y) in self.points]
class SimpleGraphicsFrame(wx.Frame):
def __init__(self, parent, *args, **kwargs):
wx.Frame.__init__(self, parent, *args, **kwargs)
# Attributes
self.panel = SimpleGraphics(self)
# Layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.panel, 1, wx.EXPAND)
self.SetSizer(sizer)
class SimpleGraphApp(wx.App):
def OnInit(self):
self.frame = SimpleGraphicsFrame(None,
title="Drawing Shapes",
size=(300, 400))
self.frame.Show()
return True
if __name__ == '__main__':
app = SimpleGraphApp(False)
app.MainLoop()
You call self.Refresh() from your OnKeyArrow and OnMotion events. Update your scene data in those methods and set some flag e.g. self.repaint_needed = True. Then in OnIdle repaint the scene if self.repaint_needed is True.
Now you try to repaint the window every time the event is received. Which may be a lot.
What you want to do is to update the scene information every time, but repaint the window only when wx indicates it has some "free time".

Radio buttons using wxpython

I'm Building a gui using wxpython.. i have buttons and radiobuttons in it, and i wanna
to do such tasks based on what the current values of the widgets in the gui .. the insert
button has a multiple if statement one of these if statement is to check whether a
radiobutton is selected. i dont want to bind an event to the radio button so i have
checked about it in the insert button using
this is the defined radion button
self.rb1 = wx.RadioButton(self.panel, -1, 'Is this a required pre_action to the next
step?', (5, 220))
and this is the check condition
if self.rb1.GetValue():
# do something here
and also :
if self.rb1.GetValue() == 'True':
# do some tasks
in both way (which is already the same) the is nothing happend when i choose the radio
button rb1 ! so what is the problwm of this ?
I don't know what that doesn't work for you. It works for me just fine. See sample code below:
import wx
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial")
panel = wx.Panel(self, wx.ID_ANY)
self.radio = wx.RadioButton(panel, label="Test", style = wx.RB_GROUP)
self.radio2 = wx.RadioButton(panel, label="Test2")
btn = wx.Button(panel, label="Check Radio")
btn.Bind(wx.EVT_BUTTON, self.onBtn)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.radio, 0, wx.ALL, 5)
sizer.Add(self.radio2, 0, wx.ALL, 5)
sizer.Add(btn, 0, wx.ALL, 5)
panel.SetSizer(sizer)
#----------------------------------------------------------------------
def onBtn(self, event):
""""""
print "First radioBtn = ", self.radio.GetValue()
print "Second radioBtn = ", self.radio2.GetValue()
# Run the program
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()

Resources