How do I do a simple math calculation on Tkinter?

Asked

Viewed 315 times

0

I’m trying to make a simple mathematical calculation in Python but when I try to use my code it doesn’t work

My code :

import tkinter as tk
from math import *

win = tk.Tk()

win.title("Calculadora de média v1.0")
win.configure(background="light blue")
win.geometry('600x500')
win.resizable(False, False)

#---------------#
lg = "light blue"
cd14 = "Candara 14"
#/\ variaveis para o background e fonte dos textos /\#

#\/ Widgets \/#

Texto1 = tk.Label(win,text = "Calculadora de média",background=lg,font="Candara 14")
Texto1.pack()

Texto2 = tk.Label(win,text = "Nota do Teste:",bg=lg,font=cd14)
Texto2.place(x=27,y=50)

Teste = tk.Entry(win)
Teste.place(x=150,y=55)

Media = Teste - 2
Texto3 = tk.Label(win,text = Media,bg=lg,font=cd14)

win.mainloop()

The mistake :

Traceback (most recent call last):
  File "C:\Users\Cauã Wernek\Desktop\pythonbook\calculadora de media\gui\pythongui.py", line 27, in <module>
    Media = Teste - 2
TypeError: unsupported operand type(s) for -: 'Entry' and 'int'

What I did wrong?

  • Potato, you are trying to subtract 2 from an object (Test - 2), it will actually generate error, what you intended with that line?

1 answer

0


The Teste that you are trying to subtract is an object of Entry, it is not a number. If you want to get its value, you must invoke the method get() which will return a string and then convert it to int. See this simple example below:

from tkinter import *

def somar():
    global resultado
    texto = entrada_de_texto.get()
    numero = int(texto)
    resultado += numero
    print("Resultado: %i"%resultado)

janela = Tk()
resultado = 0

entrada_de_texto = Entry(janela,width=10,bg="white",font=("Arial",15))
entrada_de_texto.pack()

Button(janela,text="Somar",command=somar).pack()
janela.mainloop()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.