问题
As a follow-up question to my previous post I was wondering if there is a way to navigate through multiple toggle buttons using the arrow keys?
My program needs to know which toggle button the user is currently selecting.
回答1:
This is the final solution. I know this is not a very "pythonic" or even conventionally good solution but it works.
#!/usr/bin/python
import wx
k = 0
Buttons = []
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None, title = "Gonna Get Them Cursor Keys Workin'")
self.panel = wx.Panel(self,wx.ID_ANY)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.flags_panel = wx.Panel(self, wx.ID_ANY, style = wx.SUNKEN_BORDER)
self.sizer.Add(self.flags_panel)
self.SetSizer(self.sizer,wx.EXPAND | wx.LEFT)
self.flags = Flags(self.flags_panel, [8,12])#,rows = 12, columns = 8, radius = 10, hspace = 25, vspace = 25, x_start = 15, y_start = 15
self.flags.Show()
class Flags (wx.Panel):
def __init__(self,panel, num_flags = []):#,rows = 0,columns = 0,radius = 0, hspace = 0, vspace = 0,x_start = 0, y_start = 0
wx.Panel.__init__(self,panel,-1, size = (350,700))
num_rows = num_flags[0]
num_columns = num_flags[1]
x_pos_start = 10
y_pos_start = 10
xy_coords = []
i = x_pos_start
j = y_pos_start
buttons = []
self.position_tuple_array = []
for i in range (num_columns):
buttons.append('toggle button')
self.ButtonValue = False
for button in buttons:
index = 0
while index != 15:
i += 25
index += 1
self.position_tuple_array.append((i,j))
xy_coords.append((i,j))
j += 15
i = 10
print self.position_tuple_array
global Buttons
for k in range (len(self.position_tuple_array)):
self.Button = wx.ToggleButton(self,-1,size = (10,10), pos = self.position_tuple_array[k])
self.Button.Bind(wx.EVT_KEY_DOWN,self.OnKeyPress)
Buttons.append(self.Button)
self.Button.SetFocus()
self.Button.Show()
print Buttons
#That text crap below goes here
def OnKeyPress(self,event):
button = event.GetEventObject()
keycode = event.GetKeyCode() #New Code
print keycode
global Buttons
global k
if k > len(Buttons):
k = 0
elif k < 0:
k = len(Buttons) - 1
if keycode == wx.WXK_LEFT:
print "YOU MOVED LEFT"
k -= 1
Buttons[k].SetFocus()
elif keycode == wx.WXK_RIGHT:
print "YOU MOVED RIGHT"
k += 1
Buttons[k].SetFocus()
elif keycode == wx.WXK_UP:
print "YOU MOVED UP"
k -= 15
Buttons[k].SetFocus()
elif keycode == wx.WXK_DOWN:
print "YOU MOVED DOWN"
k += 15
Buttons[k].SetFocus()
elif keycode == wx.WXK_RETURN:#End of New Code
if not self.ButtonValue:
button.SetBackgroundColour('#fe1919')
self.ButtonValue = True
else:
button.SetBackgroundColour('#14e807')
self.ButtonValue = False
print self.position_tuple_array[k]
if __name__ == '__main__':
app = wx.App(False)
frame = Frame()
frame.Show()
app.MainLoop()
来源:https://stackoverflow.com/questions/31660338/moving-through-toggle-buttons-using-arrow-keys