Python Forum

Full Version: Avoiding too many if's
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi first time here, forgive me if this has been asked before, did a search and couldn't find it.
I am writing a script to send various commands from a touch screen to a flight simulator program. There are about 30 buttons that can be pressed on two pages and I thought making a Class for the buttons might help avoid writing dozens of if statements.
The Class would look something like this
class Sim_key:
  def __init__(self, name, key_mod, key_code, x_coord, y_coord, status):
      self.name = name
      self.key_code = key_code
      self.key_mod = key_mod
      self.key_code = key_code
      self.x_coord = x_coord
      self.y_coord = y_coord
      self.status = status
So when the screen is touched I would have the x_coord and y_coord and use those (in a range like x(10,20) y(40,60)) to fire off the keyboard commands key_mod and key_code to the output routine.
Not even sure if a Class is appropriate here. Thanks
I wouldn't but depends on a few things. First is your choice of GUI. I use WX, and I would bind each button to its own routine - meaning no ifs. Of note, there is discussion about adding a switch type statement in a future Python version, but I would still think the binding method would be faster and more maintainable.
The main way in python to avoid using a lot of if conditions is to use a dictionary. We have a tutorial to give an example.
Thanks for that not familiar with WX will check it out.
Yep I'm using some dictionaries already and probably will. Tried to load wx on raspberry pi but it didn't look like an easy install. Also giving tkinter a try but may just hard code it with dictionaries as suggested.
Thanks for helping out.
Why would you need to write dozens of if statements? Your buttons will call a function. Usually different functions for different buttons. The function call can pass arguments. I am not seeing where this leads to a lot of "if statements".
Just that I'm not familiar with the GUI tools. The last project I did was a small one with only six buttons and I used pygames to blit the buttons on screen then just passed the touch coords on to a bunch of if statements.
I took a look at tkinter but it looks like a steep learning curve to do the bitmapped buttons. Though it would be much cleaner.