DEV Community

Cover image for Learning Python- Intermediate course: Day 31, Coordinate positions
Aatmaj
Aatmaj

Posted on

Learning Python- Intermediate course: Day 31, Coordinate positions

Today we will cover the coordinate layout in Tkinter


Today we will make a program which will take in inputs of principle and discount and calculate the total price.

image

Here are the program specs

  • One label for the text principle
  • One label for the text discount
  • One label for the total value
  • One button show.
  • One slider for the discount values
  • One spinbox for the principle amount

Now that we have got all the specs, let's start building the program-

from tkinter import *
master=Tk()
master.geometry("300x200")

Lbl1=Label(master,text="Principle")
Lbl2=Label(master,text="Discount")
Lbl3=Label(master,text="Total. ",font="20px")
spinbox=Spinbox(master,from_=10, to=100)
slider=Scale(master,from_=0, to=100, tickinterval=20, length= 150, orient="horizontal")
def display():
    a=int(spinbox.get())-int(spinbox.get())*int(slider.get())/100
    Lbl3.config(text=str(a)+"$")
button=Button(master,text="Calculate",command=display)

spinbox.pack()
Lbl1.pack()
slider.pack()
Lbl2.pack()
button.pack()
Lbl3.pack()

mainloop()


Enter fullscreen mode Exit fullscreen mode

image
image

The program works all right, but that's not how we want to display the widgets. We need to adjust the look and feel. We want the first two labels to be adjacent towards the spinbox and slider widgets. For that, we use the coordinate layout. The pack layout is not sufficient as it packs all the widgets into just a centre line. Hence, we will place them coordinately.

We can set the coordinates of the widgets using the place method. Example widget.place(x=30,y=20)
Here is the final program, now with the power of place layout.


from tkinter import *
master=Tk()
master.geometry("300x200")

Lbl1=Label(master,text="Principle")
Lbl2=Label(master,text="Discount")
Lbl3=Label(master,text="Total. ",font="20px")
spinbox=Spinbox(master,from_=10, to=100)
slider=Scale(master,from_=0, to=100, tickinterval=20, length= 150, orient="horizontal")
def display():
    a=int(spinbox.get())-int(spinbox.get())*int(slider.get())/100
    Lbl3.config(text=str(a)+"$")
button=Button(master,text="Calculate",command=display)

spinbox.place(x=100, y=0)
Lbl1.place(x=0,y=0)
slider.place(x=100, y=50)
Lbl2.place(x=0,y=70)
button.place(x=150,y=130)
Lbl3.place(x=150,y=170)

mainloop()

Enter fullscreen mode Exit fullscreen mode

image

image

One thing to note is that the layouts remain the same even if the window is resized.

image

Top comments (0)