Tuesday, April 22, 2025

Tkinter - Get Value From Entry Fields

In this tutorial we will combine knowledge from previous scripts.

We have only one Label with corresponding Entry field. There is also submit button, but it's not yet connected to real function that will do processing. 

Place where we will see results will be inside dedicated Canvas. This is important to note.

Once we have that arrangement, we can continue with dedicated function that will do something.

So far, this is full working script:

from tkinter import *
import tkinter.messagebox as mb
import os

top_win = Tk()
top_win.geometry("800x800")
        
lab_1 = Label(top_win, text = "Number", bg = "lightyellow")
lab_1.grid(row = 0, column = 0)

ent_1 = Entry(top_win)
ent_1.grid(row = 0, column = 1)

but_1 = Button(top_win, text = "Calculate", bg = "lightgreen")
but_1.grid(row = 1, column = 0)

c = Canvas(top_win, width = 100, heigh = 100, bg = "yellow")
c.grid(row = 2, column = 3)      

top_win.mainloop()

Ok, now it is the time to create function that will get values from entry field with get() method. Once we have data, we can do some simple calculations.

But we also need to have again Canvas to show results there using lab_2 label that deals with text values. This is whole source of function:

def calculate_func():
    number_atm = ent_1.get()
    print_res = (int(number_atm) * 2)

    c = Canvas(top_win, width = 100, heigh = 100, bg = "yellow")
    c.grid(row = 2, column = 3)

    lab_2 = Label(c)
    lab_2["text"] = print_res
    lab_2.grid(row = 1, column = 1)

Once we combine all needed a source, function, label, entry field, Canvases, this is full working script that will process and show results.

And yes, my best advice is to go through dedicated YT tutorial that covers Getting Values from Entry Field in Tkinter.

from tkinter import *
import tkinter.messagebox as mb
import os

top_win = Tk()
top_win.geometry("800x800")

def calculate_func():
    number_atm = ent_1.get()
    print_res = (int(number_atm) * 2)

    c = Canvas(top_win, width = 100, heigh = 100, bg = "yellow")
    c.grid(row = 2, column = 3)

    lab_2 = Label(c)
    lab_2["text"] = print_res
    lab_2.grid(row = 1, column = 1)
        
lab_1 = Label(top_win, text = "Number", bg = "lightyellow")
lab_1.grid(row = 0, column = 0)

ent_1 = Entry(top_win)
ent_1.grid(row = 0, column = 1)

but_1 = Button(top_win, text = "Calculate", bg = "lightgreen", command = calculate_func)
but_1.grid(row = 1, column = 0)

c = Canvas(top_win, width = 100, heigh = 100, bg = "yellow")
c.grid(row = 2, column = 3)      

top_win.mainloop()

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...