if/elif mash up
The if
statement, and it's complement elif
, work on Boolean values. If a variable, or whatever is being tested, is not Boolean already, then it is coerced and understood in a true/false fashion.
Any object that is non-zero, and not empty, is interpreted as being "True". So, assuming that dec_bttn
and hex_bttn
are Tkinter checkboxes, then Python is checking the Boolean value of the checkboxes themselves and, seeing that they are true, proceeds to execute the first if
block every time.
Somewhere in your code you're probably initializing the Tkinter checkboxes like this:
self.dec_bttn = Checkbutton(root, Text='To decimal', ... )self.hex_bttn = Checkbutton(root, Text='To hex', ... )
Instead of initializing them like this, you need to have variables that can store the "checked" state of the checkboxes, like so:
self.dec_checked = IntVar()self.hex_checked = IntVar()self.dec_bttn = Checkbutton(root, Text='To decimal', variable=self.dec_checked, ... )self.hex_bttn = Checkbutton(root, Text='To hex', variable=self.hex_checked, ... )
Notice the IntVar
. That is where the value is stored. But, you don't have to use IntVar
, you can also use BooleanVar
, or any other Tkinter variable type, in fact.
But, I digress, I see that you're already using a BooleanVar
. So, most of this you already knew. But, the reason why just checking self.dec_bttn
doesn't work is because dec_bttn
is an object, not just a simple Boolean value.
Use self.dec_bttn.get()
in your if
statement to check the states of the checkboxes.
Check out the Tkinter reference for some other methods that are associated with the Tkinter variable types.
It sounds like you self.dec_bttn
and self.hex_bttn
evaluate to true, probably because, as @voithos says, you should .get()
the values from the objects.
Here is a perfectly serviceable binary-string-to-number converter:
def binary_to_number(binary_string): total = 0 for c in binary_string: total = total * 2 + (c == "1") return total
Then your code could be like this:
def binary_to_number(binary_string): total = 0 for c in binary_string: total = total * 2 + (c == "1") return totaldef binary_to_decimal(binary_string): return str(binary_to_number(binary_string))def binary_to_hex(binary_string): hex_digits = { 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f' } tot = binary_to_number(bits) return str(hex_digits.get(tot, tot))if self.dec_bttn.get(): self.output_disp.delete(0.0, END) self.output_disp.insert(0.0, binary_to_decimal(bits))elif self.hex_bttn.get(): self.output_disp.delete(0.0, END) self.output_disp.insert(0.0, binary_to_hex(bits))