1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TkinterでHEXで表示可能なSpinboxを作る

Last updated at Posted at 2020-07-13

Python GUI TkinterでHEXで表示可能なSpinboxを作る。

HEX.png

Tkinterではformatオプションを使ってもSpinboxがHEX対応していません。
ただ、内部的な加算などはHEX対応しているものと思われます。
(increment=1はHEXでも有効)
バイト数を明示的に示すサンプルプログラムを下記のように記載してみました。

HexSpinbox.py
import tkinter as tk

class HexSpinbox(tk.Spinbox):
    def __init__(self, *args, **kwargs):
        self.var = tk.StringVar()
        self.bytenum = kwargs.pop('bytenum')
        max_val = 0x1<<(self.bytenum*8)
        super().__init__(*args, **kwargs, textvariable=self.var, from_=0,to=max_val,
                         increment=1, command=self.cange )

    def set(self, val):
        s = "0x{:0%dx}" % (self.bytenum*2)
        self.var.set(s.format(int(val)))
        
    def get(self):
        hstr = super().get()
        return int(hstr, 16)

    def cange(self):
        val = super().get()
        self.set(val)


if __name__ == "__main__":
    print("HexSpinbox")
    win = tk.Tk()
    hex = HexSpinbox(win, bytenum=2)
    hex.set(0xAA55)
    hex.pack()
    
    win.title("HexSpinbox test")
    win.mainloop()


1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?