简体   繁体   中英

Format String for tk.Listbox

I want to fill a tk.Listbox. On the left side there should be the names of the indicators (left-justified), on the right side the values and the units (right-justified). There are some... in between.

In Jupyter it works:

enter image description here

In a GUI it looks like this:

enter image description here

The code is:

for name, value in zip(content_name, content_value):
    points = 34 - len(name) - len(value)
    in_between = "........"
    for p in range(points):
        in_between = in_between + "."
    content = name + in_between + value
    listbox_record.insert(tk.END, content)

Is there a way to do this in a GUI without knowing the font or the specific length of a character in pixels?

Thanks!

As suggested by acw1668, I've set the font to a mono spaced font ("Courier", 9). I believe TKinter default font is ("New Courier", 9).

### Frame Listbox
frame_listbox = tk.Frame(self.frame_activities)
frame_listbox.grid(row = 1, column = 0, columnspan = 2, sticky = "ew", padx = 10)
        
### Frame Scrollbar
frame_scroll_select_activity = tk.Frame(frame_listbox)
scrollbar_select_activity = tk.Scrollbar(frame_scroll_select_activity, orient = tk.VERTICAL)
 
### Font Listbox
font_listbox = ("Courier", 9)       

### Listbox 
listbox_record = tk.Listbox(frame_scroll_select_activity, font = font_listbox, width = 42, yscrollcommand = scrollbar_select_activity.set, selectmode = tk.SINGLE)
    
### Configure Scrollbar 
scrollbar_select_activity.config(command = listbox_record.yview)
    
### Packing
scrollbar_select_activity.pack(side = tk.RIGHT, fill = tk.Y)    
frame_scroll_select_activity.pack()
listbox_record.pack(pady = 10) 

Fill listbox...

for name, value in zip(content_name, content_value):
    content = name + value.rjust(42 - len(name), ".")
    listbox_record.insert(tk.END, content)

And it looks like that...

Listbox

Very cool!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM