Home > Software design >  Suggestion on how to print result from function into a label field with Tkinter python
Suggestion on how to print result from function into a label field with Tkinter python

Time:12-18

Trying to get a result from a function to print to a empty label using tkinker gui. Ive searched and tried myself, but i cannot figgure out how to do this. Its no problem to get it to print to the terminal, but into a label it will not. Ive been watching youtube tutorials and trying to hack something togher myself. I encounter alot of obstacles, but learning this skill is so amazing :) If anyone can help me out with this problem i will be grateful!

Code below:

from tkinter import *

root = Tk()

#Labels
head_label = Label(text="Calculates weight pr meter:")
weight_plank_label = Label(text="Weight in gram:")
lenght_plank_label = Label(text="Lenght in mm:")

#Entry field
weight_entry = Entry(root)
lenght_entry = Entry(root)

#Text field label
weight_meter_show = Label(root, text="FUNCTION RESULT HERE", height=1, width=20)   # Want result from "def weight():" to show in this Text box

#Calc weight function
def weight():
    x = weight_entry.get()
    y = lenght_entry.get()
    z = (int(x) / int(y))
    print(z) 

#Button
calc_btn = Button(height=1, width=8, text="Calculate", command=weight)

#Shoving it to root window
head_label.grid(row=0, column=0)
weight_plank_label.grid(row=1, column=0)
lenght_plank_label.grid(row=2, column=0)
weight_entry.grid(row=1, column=1)
lenght_entry.grid(row=2, column=1)
calc_btn.grid(row=3, column=0)
weight_meter_show.grid(row=4, column=0)

root.mainloop()

CodePudding user response:

Like Tim Robert say's, just add :

weight_meter_show.config( text=str(z))

instead of print in your weight def.

    def weight():
      x = weight_entry.get()
      y = lenght_entry.get()
      z = (int(x) / int(y))
      weight_meter_show.config(text=str(z))
  • Related