11

For a tkinter GUI, I must read in a Hex address in the form of '0x00' to set an I2C address. The way I am currently doing it is by reading the input as a string, converting the string to an integer, then converting that integer to an actual Hex value as shown in the partial code below:

GUI initialization:

self.I2CAddress=StringVar()
self.I2CAddress.set("0x00") #Sets Default value of '0x00'
Label(frame, text="Address: ").grid(row=5, column=4)
Entry(frame, textvariable=self.I2CAddress).grid(row=5, column=5)

Then inside the function:

addr = self.I2CAddress.get()   
addrint = int(addr, 16)  
addrhex = hex(addrint)

This works for most values, but my issue is that if I enter a small Hex value string such as '0x01', it converts to the proper integer of 1, but then that is converted to a Hex value of 0x1 instead of 0x01.

I am an EE and have very limited programming experience, so any help is greatly appreciated.

1 Answer 1

19

Use the format() function:

format(addrint, '#04x')

This formats the input value as a 2 digit hexadecimal string with leading zeros to make up the length, and # includes the 'standard prefix', 0x in this case. Note that the width of 4 includes that prefix. x produces lower-case hex strings; use X if you need uppercase.

Demo:

>>> for i in range(8, 12):
...     print format(i, '#04x')
... 
0x08
0x09
0x0a
0x0b
Sign up to request clarification or add additional context in comments.

9 Comments

You answered so quickly I have to wait a few minutes before it allows me, but I absolutely will
You can just use {:#02x} instead of the explicit 0x. The # will add the "standard prefix", which for hex numbers is 0x. (This also works the same way with %-formatting, and C printf, and POSIX command-line printf, etc.)
@abarnert: Cool, I was not aware of the # prefix option.
@abarnert: Slight snag: # removes the leading zeros again. That, to me, looks like a bug, it appears as if the width is ignored altogether.
@abarnert: With the # prefix you can just use the format() function and completely dispense with the string templating altogether.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.