[Tutor] Tkinter, the correct way

Phil phillor9 at gmail.com
Fri Feb 10 04:00:07 EST 2023


There are a dozen ways to achieve the same thing in Tkinter due to 
backward compatibility so I bought an e-book that promised to show the 
correct modern way. The code is an example of something that I'd written 
some time ago and now modified (improved, maybe).

A few questions, if I may.

Is this code the correct modern way?

I don't notice any difference If I omit the frame padding and grid options.

VS Code issues warnings to do with import * and value_label = etc is a 
function without a return. The latter can probably be quelled with a VS 
Code option but I'm not sure about import *.

Finally, moving the scale with the arrow keys show integers but moving 
the scale with the mouse cause the scale value to be a long floating 
point number. How might I have the value variable be an integer when the 
mouse is moved?

from tkinter import *
from tkinter import ttk


class ScaleDemo:

     def __init__(self, root):

         root.title("Scale Demo")

         frame = ttk.Frame(root, padding="3 3 12 12")
         frame.grid(column=0, row=0, sticky=(N, S, E, W))

         root.columnconfigure(0, weight=1)
         root.rowconfigure(0, weight=1)

         self.value = DoubleVar()

         slider = ttk.Scale(
             frame,
             from_=0,
             to=100,
             orient='horizontal',  # vertical
             command=self.slider_changed,
             variable=self.value)

         slider.grid(column=2, row=1, sticky=(E, W))

         value_label = ttk.Label(frame, textvariable=self.value).grid(
             column=2, row=2, sticky=(W, E))

         ttk.Button(frame, text="Exit", command=root.destroy).grid(
             column=3, row=3, sticky=W)

         for child in frame.winfo_children():
             child.grid_configure(padx=5, pady=5)

         slider.focus()

     def slider_changed(self, event):
         #print('value changed')
         print(f'{self.value.get():,.1f}')


root = Tk()
ScaleDemo(root)
root.mainloop()

-- 
Regards,
Phil



More information about the Tutor mailing list