Python/Tkinter - - python

I am developing an application to calculate the billing tax, and at the same time, if the value of the calculation base ((receita1 * 32/100) + (receita2 * 8/100)) is greater than 60k, it calculates the surplus of that, (((receita1 * 32/100) + (receita2 * 8/100)) - 60000), however is giving the following error:
v_result3.set(real(receita1 * 32 / 100) + (receita2 * 8 / 100))
TypeError: can only concatenate str (not "float") to str
Here is the complete code:
from tkinter import *
root = Tk()
root.geometry('350x350')
def real(my_value):
a = '{:,.2f}'.format(float(my_value))
b = a.replace(',', 'v')
c = b.replace('.', ',')
return c.replace('v', '.')
l_label = Label(root, text='Receita 1')
l_label.place(x=10, y=10)
e_entry = Entry(root)
e_entry.place(x=100, y=10)
l_label2 = Label(root, text='Receita 2')
l_label2.place(x=10, y=40)
e_entry2 = Entry(root)
e_entry2.place(x=100, y=40)
v_result = DoubleVar()
l_result = Label(root, textvariable=v_result)
l_result.place(x=10, y=70)
l_explic = Label(root, text='<-- receita1 x 32%')
l_explic.place(x=100, y=70)
v_result2 = DoubleVar()
l_result2 = Label(root, textvariable=v_result2)
l_result2.place(x=10, y=100)
l_explic2 = Label(root, text='<-- receita2 x 8%')
l_explic2.place(x=100, y=100)
v_result3 = DoubleVar()
l_result3 = Label(root, textvariable=v_result3)
l_result3.place(x=10, y=130)
l_explic3 = Label(root, text='<-- receita1 x 32% + receita2 x 8%')
l_explic3.place(x=100, y=130)
v_result4 = DoubleVar()
l_result4 = Label(root, textvariable=v_result4)
l_result4.place(x=10, y=160)
l_explic4 = Label(root, text='<-- result if')
l_explic4.place(x=100, y=160)
def calc():
receita1 = int(e_entry.get())
receita2 = int(e_entry2.get())
v_result.set(real(receita1 * 32 / 100))
v_result2.set(real(receita2 * 8 / 100))
v_result3.set(real(receita1 * 32 / 100) + (receita2 * 8 / 100))
if v_result3.get() > 60000:
v_result4.set(real((receita1 * 32 / 100) + (receita2 * 8 / 100)) - 60000)
elif v_result3.get() < 60000:
v_result4.set(real(receita1 * 32 / 100) + (receita2 * 8 / 100))
e_entry.delete(0, END)
e_entry2.delete(0, END)
bt = Button(root, text='calc', command=calc)
bt.place(x=10, y=200)
root.mainloop()

You're seeing this problem because you're mixing and matching numbers formatted as strings and numbers themselves.
It's better to form your computation into input / computation / output. I've also taken the liberty to use Decimal numbers instead of plain integers, since you seem to be dealing with money, and precision is generally tantamount in that domain.
from decimal import Decimal
from tkinter import *
root = Tk()
root.geometry("350x350")
l_label = Label(root, text="Receita 1")
l_label.place(x=10, y=10)
e_entry = Entry(root)
e_entry.place(x=100, y=10)
l_label2 = Label(root, text="Receita 2")
l_label2.place(x=10, y=40)
e_entry2 = Entry(root)
e_entry2.place(x=100, y=40)
v_result1 = StringVar()
l_result1 = Label(root, textvariable=v_result1)
l_result1.place(x=10, y=70)
l_explic1 = Label(root, text="<-- receita1 x 32%")
l_explic1.place(x=100, y=70)
v_result2 = StringVar()
l_result2 = Label(root, textvariable=v_result2)
l_result2.place(x=10, y=100)
l_explic2 = Label(root, text="<-- receita2 x 8%")
l_explic2.place(x=100, y=100)
v_result3 = StringVar()
l_result3 = Label(root, textvariable=v_result3)
l_result3.place(x=10, y=130)
l_explic3 = Label(root, text="<-- receita1 x 32% + receita2 x 8%")
l_explic3.place(x=100, y=130)
v_result4 = StringVar()
l_result4 = Label(root, textvariable=v_result4)
l_result4.place(x=10, y=160)
l_explic4 = Label(root, text="<-- result if")
l_explic4.place(x=100, y=160)
def real(my_value):
return str(my_value.quantize(Decimal("0.02"))).replace(".", ",")
def calc():
# Get inputs
receita1 = Decimal(int(e_entry.get()))
receita2 = Decimal(int(e_entry2.get()))
# Compute
result1 = receita1 * Decimal("0.32")
result2 = receita2 * Decimal("0.08")
result3 = receita1 + receita2
if result3 > 60000:
result4 = result3 - 60000
else:
result4 = result3
# Output
v_result1.set(real(result1))
v_result2.set(real(result2))
v_result3.set(real(result3))
v_result4.set(real(result4))
e_entry.delete(0, END)
e_entry2.delete(0, END)
bt = Button(root, text="calc", command=calc)
bt.place(x=10, y=200)
root.mainloop()

Related

Destroying a label in Tk

I've wracked my brain about this. I'm new to Python and Tk,and just trying it out. I would think this would be really easy, but I can't get it. Here's my code:
from tkinter import *
window = Tk()
window.geometry = ('400x200')
mylabel = Label(window)
def button_command():
Label(window).destroy()
text = entry1.get()
selection=variable.get()
if selection == "Celsius":
f = "Fahrenheit: " + str(round((int(text) - 32) * 5/9,2))
mylabel = Label(window, text = f).pack()
else:
c = "Celsuius: " + str(round((int(int(text)) * 9/5) + 32))
mylabel = Label(window, text = c).pack()
return None
def clear_label():
mylabel.destroy()
entry1 = Entry(window, width = 20)
entry1.pack()
variable = StringVar(window)
variable.set("Fahrenheit") # default value
w = OptionMenu(window, variable, "Fahrenheit", "Celsius")
w.pack()
Button(window, text="Button", command=button_command).pack()
Button(window, text="Clear", command=clear_label).pack()
window.mainloop()
I don't get an error, but the clear_label function doesn't do anything. It doesn't return an error. It just doesn't work. Any suggestions would be appreciated. :)
You never actually packed the label into the window, therefore there was nothing to destroy. If you run this code, you can see that once packed, your function works as expected.
from tkinter import *
window = Tk()
window.geometry = ('400x200')
mylabel = Label(window, text="test")
def button_command():
Label(window).destroy()
text = entry1.get()
selection=variable.get()
if selection == "Celsius":
f = "Fahrenheit: " + str(round((int(text) - 32) * 5/9,2))
mylabel = Label(window, text = f).pack()
else:
c = "Celsuius: " + str(round((int(int(text)) * 9/5) + 32))
mylabel = Label(window, text = c).pack()
return None
def clear_label():
mylabel.destroy()
mylabel.pack
entry1 = Entry(window, width = 20)
entry1.pack()
variable = StringVar(window)
variable.set("Fahrenheit") # default value
w = OptionMenu(window, variable, "Fahrenheit", "Celsius")
mylabel.pack()
Button(window, text="Button", command=button_command).pack()
Button(window, text="Clear", command=clear_label).pack()
window.mainloop()
Not sure whether the aim of the exercise is to destroy a label or just clear the label and give it a new value. If it is the latter, it can be achieved using the text variable parameter to label.
from tkinter import *
def button_command():
text = entry1.get()
selection=variable.get()
# Change the value of the stringvar to set the new value
if selection == "Celsius":
labelvalue.set("Fahrenheit: " + str(round((int(text) - 32) * 5/9,2)))
else:
labelvalue.set("Celsuius: " + str(round((int(int(text)) * 9/5) + 32)))
return None
def clear_label():
# No need to destroy - just change the value
labelvalue.set("")
window = Tk()
window.geometry = ('400x200')
entry1 = Entry(window, width = 20)
entry1.pack()
variable = StringVar(window)
variable.set("Fahrenheit") # default value
w = OptionMenu(window, variable, "Fahrenheit", "Celsius")
w.pack()
Button(window, text="Button", command=button_command).pack()
Button(window, text="Clear", command=clear_label).pack()
# The text displayed in mylabel will be the contents of labelvalue
labelvalue = StringVar()
mylabel = Label(window, textvariable=labelvalue)
mylabel.pack()
window.mainloop()
In principle, you don't have to delete and re-create the Label, just clear the fields in the Label and in the Entry:
def clear_label():
mylabel.config(text="")
entry1.delete(0, 'end')

if a user enters a fraction as one of the values of the matrix that it will simply convert to float [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to fill in a matrix, and at the same time if a for example "1/7" get entered that it converts to float ? but it doesn't work
import fractions
import tkinter as tk
from tkinter import *
import numpy as np
import pandas as pd
from fractions import Fraction
from tkinter.font import Font
from PIL import Image, ImageTk
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
import tkinter.messagebox
import os
import sys
#this function contain a small window that you need to put the number of criteria in ,which will be the dimension of the maTRIX , WHEN I FILL THE matrix and click submit for it to be saved it doesn't work
def be():
window = Tk()
window.title("Dimensions ")
window.geometry("300x200")
def variable():
global fn, f
fn = entry_1.get()
f = entry_2.get()
ln = StringVar()
df = []
name = StringVar()
def save():
for entries in range(len(df)):
df[entries] = name.get()
for entries in range(len(df)):
df = df.append({'Critere': df[entries].get()}, ignore_index=True)
print(df)
df
def open_window():
root = tk.Tk()
root.geometry("460x600")
root.title('AHP Application ')
# global f
# f=printent()
# print(f)
for i in range(int(f)):
# c = input("Enter valeur {}: ".format(i))
my_label = Label(root, text="Entrer le critere numero 0{} :".format(i + 1), width=24, font=("bold", 10))
my_label.grid(row=i, column=0, pady=20, padx=5)
my_entry = Entry(root)
my_entry.grid(row=i, column=1, pady=20, padx=5)
df.append(my_entry)
suivant1 = tk.Button(root, text="Suivant", width=8, borderwidth=3, command=hope).place(x=370, y=40)
fermer2 = tk.Button(root, text="Fermer", width=8, borderwidth=3).place(x=370, y=90)
root.mainloop()
label_1 = Label(window, text="Entrer L'Objectif de Votre projet :", width=24, font=("bold", 10))
label_1.place(x=3, y=0)
entry_1 = Entry(window)
entry_1.place(x=100, y=30)
label_2 = Label(window, text="Entrer le nombre de critère :", width=20, font=("bold", 10))
label_2.place(x=3, y=70)
entry_2 = Entry(window)
# Remove default 0
entry_2.delete(0, END)
entry_2.place(x=100, y=100)
suivant = tk.Button(window, text="suivant", borderwidth=3, command=lambda: [variable(), open_window()]).place(x=40,
y=150)
fermer = tk.Button(window, text="fermer", borderwidth=3).place(x=190, y=150)
def hope():
win = Tk()
win.title("Matrix")
win.geometry("700x500")
global f
print(f)
wrapper1 = LabelFrame(win, text="Enter matrix")
wrapper3 = LabelFrame(win, text="Resultats")
wrapper1.pack(fill="both", expand="yes", padx=50, pady=20)
wrapper3.pack(fill="both", expand="yes", padx=20, pady=10)
def convert_to_float(frac_str):
try:
return float(frac_str)
except ValueError:
num, denom = frac_str.split('/')
try:
leading, num = num.split(' ')
whole = float(leading)
except ValueError:
whole = 0
frac = float(num) / float(denom)
return whole - frac if whole < 0 else whole + frac
# empty arrays for your Entrys and StringVars
text_var = []
entries = []
matrix = []
# callback function to get your StringVars
def get_mat():
for i in range(rows):
matrix.append([])
for j in range(cols):
matrix[i].append(convert_to_float (text_var[i][j].get()))
print(matrix)
b = np.array(matrix, dtype=float, order='C')
print(b)
global df2, df, c
index = []
columns = []
for i in range(int(f)):
index.append("critère{}".format(i + 1))
columns.append("critère{}".format(i + 1))
df = pd.DataFrame(data=b, index=index, columns=columns)
print(df)
arr = df.to_numpy()
global c
c = []
for i in range(len(df)):
c.append(np.prod(arr[i].astype(float)))
df2 = pd.DataFrame(data=c, index=range(int(f)), columns=["hi"])
print(df2)
# Label(win, text="Enter matrix :", font=('arial', 10, 'bold'),
# bg="bisque2").place(x=20, y=20)
x2 = 0
y2 = 0
rows = int(f)
cols = int(f)
global df2, df, c
x = np.array(['1.1', '2.2', '3.3'])
for i in range(rows):
# append an empty list to your two arrays
# so you can append to those later
text_var.append([])
entries.append([])
for j in range(cols):
# append your StringVar and Entry
text_var[i].append(StringVar())
entries[i].append(Entry(win, textvariable=text_var[i][j], width=5))
entries[i][j].place(x=80 + x2, y=30 + y2)
x2 += 40
y2 += 30
x2 = 0
button = Button(wrapper1, text="Submit", bg='bisque3', width=15, command=get_mat)
button.place(x=300, y=80)
my_label = Label(wrapper3, text="Lamda Max:", width=24, font=("bold", 10))
my_label.grid(row=0, column=0, pady=20, padx=5)
my_entry = Entry(wrapper3)
my_entry.grid(row=0, column=1, pady=20, padx=5)
# my_entry.insert(0,lamba)
my_label1 = Label(wrapper3, text="Indice de Coherence (CI):", width=24, font=("bold", 10))
my_label1.grid(row=1, column=0, pady=20, padx=5)
my_entry1 = Entry(wrapper3)
my_entry1.grid(row=1, column=1, pady=20, padx=5)
my_label2 = Label(wrapper3, text="Indice de Racio (IC):", width=24, font=("bold", 10))
my_label2.grid(row=2, column=0, pady=20, padx=5)
my_entry2 = Entry(wrapper3)
my_entry2.grid(row=2, column=1, pady=20, padx=5)
def calcule():
global f
df3 = pd.DataFrame(data=c, index=range(int(f)))
df3 = pow(df2, 1 / int(f))
print("df3 is ")
print(df3)
# Somme
Somme = df3.sum()
print("la somme est ")
print(Somme)
# weights
B = df3 / Somme
print(" La matrice des Poids:")
print(B)
# verify if somme of B is 1 , if it is then we are on the right road
Somm = B.sum()
print(Somm)
# consistency check
print("A3")
C = np.dot(df, B)
print(C)
# consistency check
print("A4")
D = C / B
print(D)
# global lamba
# Consistency Index
# lambda
lamba = np.mean(D)
print("the average is ")
print(lamba.to_string())
my_entry.insert(0, lamba.to_string(index=False))
# n = float(n)
CI = (lamba - float(f)) / (float(f) - 1)
print("The consistency Index is")
print(CI.to_string())
my_entry1.insert(0, CI.to_string(index=False))
# consistency ratio
if int(f) == 3:
RI = 0.52
elif int(f) == 4:
RI = 0.89
elif int(f) == 5:
RI = 1.11
elif int(f) == 6:
RI = 1.25
elif int(f) == 7:
RI = 1.35
elif int(f) == 8:
RI = 1.4
elif int(f) == 9:
RI = 1.45
elif int(f) == 10:
RI = 1.49
print("THE RATIO IS :")
print(RI)
CR = float(CI / RI)
my_entry2.insert(0, CR)
if CR < 0.1:
print("Congratulations ,Your criterias are consistent to go ahead \nThe value of consistency ratio is ",
CR,
"which is less han 0.1 ")
else:
print("you need to re-fill the matrix", CR)
button = Button(wrapper3, text="calcule", bg='bisque3', width=15, command=calcule)
button.place(x=500, y=100)
a = IntVar()
win.mainloop()
window.mainloop()
be()
Python actually has a built-in module just for this, which also has support for arbitrary-precision arithmetic and conversion to native floats.
>>> from fractions import Fraction
>>> frac = Fraction("1/7")
>>> float(fract)
0.14285714285714285
Easy to use, and works out-of-the-box. You can also convert it to an integer ratio, in case you want more accuracy than a native float can provide:
>>> frac.as_integer_ratio()
(1, 7)
The reason why float("1/7") doesn't work is because it's not a valid representation of an actual float: it's an integer ratio. Fractions, however, which provides native conversion to-and-from floats, does.

Can't multiply sequence by non-int of type 'list' with user selected list item

When I do my button click it keeps throwing the error
Can't multiply sequence by non-int of type 'list'
I am unsure what to do to fix this. I have tried to change Frequnit to an int and it doesn't work. I am unsure of the syntax to correct this.
Frequnit is used for user selection of just one unit from the list
#freecodecamp.org
import math
from tkinter import *
root = Tk()
Frequnit = {
'Hz' : (10**0),
'KHz' : (10**3),
'MHz' : (10**6),
'GHz' : (10**9),
'THz' : (10**12),
}
#creating entry
f1 = Entry (root)
d1 = Entry (root, width= 4)
Gtx1 = Entry (root, width= 4)
Grx1 = Entry (root, width= 4)
MYSUT_TX1 = Entry (root, width= 5)
f1.grid (row=1, column=1)
d1.grid (row=2, column=1)
Gtx1.grid (row=3, column=1)
Grx1.grid (row=4, column=1)
MYSUT_TX1.grid (row=8, column=1)
def myClick():
#variables
c = (2.99 * (10**8))
d = float(d1.get())
f = (float(f1.get())*(Frequnit[]))
Gtx = float(Gtx1.get())
Grx = float(Grx1.get())
FSPL_cal1 = round(abs((20 * math.log10(d)) + (20 * math.log10(f)) + (20 * math.log10( (4 * math.pi ) / c ))) - Gtx - Grx,2)
FSPL_cal2 = round(abs((20 * math.log10(d)) + (20 * math.log10(f)) + (20 * math.log10( (4 * math.pi ) / c ))) - Gtx - Grx +6,2)
#Output1 GUI
FSPL = Label(root, text="FSPL ONE-WAY")
FSPL2 = Label(root, text="FSPL TWO-WAY")
FSPL_cal1 = Label(root, text=FSPL_cal1 )
FSPL_cal2 = Label(root, text=FSPL_cal2)
FSPL.grid (row=6, column=0)
FSPL_cal1.grid (row=6, column=1)
FSPL2.grid (row=7, column=0)
FSPL_cal2.grid (row=7, column=1)
def myClick2():
#variables
c = (2.99 * (10**8))
d = float(d1.get())
f = (float(f1.get())*(10**6))
Gtx = float(Gtx1.get())
Grx = float(Grx1.get())
FSPL_cal1 = round(abs((20 * math.log10(d)) + (20 * math.log10(f)) + (20 * math.log10( (4 * math.pi ) / c ))) - Gtx - Grx,2)
FSPL_cal2 = round(abs((20 * math.log10(d)) + (20 * math.log10(f)) + (20 * math.log10( (4 * math.pi ) / c ))) - Gtx - Grx +6,2)
MYSUT_TX = float(MYSUT_TX1.get())
FSPL_cal1 = round(abs((20 * math.log10(d)) + (20 * math.log10(f)) + (20 * math.log10( (4 * math.pi ) / c ))) - Gtx - Grx,2)
TargetSUT_RX = round((MYSUT_TX - FSPL_cal1),2)
Target_TX = (TargetSUT_RX -6)
MYSUT_TX = Label(root, text=TargetSUT_RX )
Target_TX = Label(root, text=Target_TX )
MYSUT_TX.grid (row=10, column=1)
Target_TX.grid (row=11, column=1)
#creating label widget
Title = Label( root, text="Free Space Loss Calculator")
Frequency = Label(root, text="Frequency")
Distance = Label(root, text="Distance")
Tx_Gain = Label(root, text="Transmit Gain")
Rx_Gain = Label(root, text="Recieve Gain")
FSPL = Button(root, text="Free Space Path loss Calculation", command=myClick)
MYSUT_TX= Label(root, text="SUT Transmit Power")
TargetPW = Button(root, text="Power Recieved at Target", command=myClick2)
MYSUT_RX= Label(root, text="Power Recieved at target")
Target_TX= Label(root, text="Return Power from target")
Tx_Gain1 = Label(root, text="dB")
Rx_Gain1 = Label(root, text="dB")
FSPL_1WAY = Label(root, text="dB")
FSPL_2WAY = Label(root, text="dB")
#drop down items
FrequencyUnits = StringVar()#dBm, uWatts, mWatts, Watts, KWatts, MWatts)
DistanceUnits = StringVar()
PowerUnits = StringVar()
FrequencyUnits.set ('Hz')
DistanceUnits.set ("Meters")
PowerUnits.set ("dBm")
# dBm = input()
# uWatts = 10* math.log10(1000*input()) * 10**-6
# mWatts = 10* math.log10(1000*input()) * 10**-3
# Watts = 10* math.log10(1000*input())
# KWatts = 10* math.log10(1000*input()) * 10**3
# MWatts = 10* math.log10(1000*input()) * 10**6
dropFreq = OptionMenu (root, FrequencyUnits, "Hz", "KHz", "MHz", "GHz", "THZ")
dropDist = OptionMenu (root, DistanceUnits, "Inches", "Feet", "Yards","Meters", "Miles", "NMI")
droppower = OptionMenu (root, PowerUnits, "dBm", "uWatts", "mWatts","Watts", "KWatts", "MWatts")
dropPRT = OptionMenu (root, PowerUnits, "dBm", "uWatts", "mWatts","Watts", "KWatts", "MWatts")
dropRPFT = OptionMenu (root, PowerUnits, "dBm", "uWatts", "mWatts","Watts", "KWatts", "MWatts")
#GUI lay out
Title.grid (row=0, column=1)
Frequency.grid (row=1, column=0)
Distance.grid (row=2, column=0)
Tx_Gain.grid (row=3, column=0)
Rx_Gain.grid (row=4, column=0)
FSPL.grid (row=5, column=1)
MYSUT_TX.grid (row=8, column=0)
TargetPW.grid (row=9, column=1)
MYSUT_RX.grid (row=10, column=0)
Target_TX.grid (row=11, column=0)
dropFreq.grid (row=1, column=2)
dropDist.grid (row=2, column=2)
Tx_Gain1.grid (row=3, column=2)
Rx_Gain1.grid (row=4, column=2)
FSPL_1WAY.grid (row=6, column=2)
FSPL_2WAY.grid (row=7, column=2)
FSPL_2WAY.grid (row=7, column=2)
droppower.grid (row=8, column=2)
dropPRT.grid (row=10, column=2)
dropRPFT.grid (row=11, column=2)
root.mainloop()
You have 2 entry boxes, so my guess is that 1 is for a number entry and the 2nd is for a frequency entry.
f1 = number entry
d1 = frequency entry
If so I would code it as follows:
def myClick():
for key in Frequnit.keys():
if key == d1.get():
result = float(f1.get()) * Frequnit[key]
resultLabel = Label(root, text=str(result)+' '+key)
resultLabel.pack()
You can't turn a whole dictionary to a number, but you can access the values by referencing the key. Saying Frequnit['Hz'] is the same as saying (10**0).
I used the for and if statements for entry validation. You can get rid of those 2 lines and use Frequnit[d1.get()] and get the same result (assuming d1 is found in the dict keys).

Python/Tkinter - change the "." through the ","

I am developing an application for calculating taxes on revenue, the code itself works normally, but i would like to know if there is a way to change the "." by "," when typing in the entry fields.
Example: 100,50 instead of 100.50
Follow the code below:
from tkinter import *
# ---
root = Tk()
root.geometry('350x350')
# ---
l_receita1 = Label(root, text='Receita 1')
l_receita1.place(x=10, y=10)
e_receita1 = Entry(root)
e_receita1.place(x=100, y=10)
l_receita2 = Label(root, text='Receita 2')
l_receita2.place(x=10, y=40)
e_receita2 = Entry(root)
e_receita2.place(x=100, y=40)
# ---
v_result1 = DoubleVar()
l_resRec1 = Label(root, textvariable=v_result1)
l_resRec1.place(x=10, y=100)
v_result2 = DoubleVar()
l_resRec2 = Label(root, textvariable=v_result2)
l_resRec2.place(x=10, y=140)
v_result3 = DoubleVar()
l_resRec3 = Label(root, textvariable=v_result3)
l_resRec3.place(x=10, y=220)
# ---
def calc():
v_result1.set(round(float(e_receita1.get()) * 8 / 100, 2))
v_result2.set(round(float(e_receita2.get()) * 12 / 100, 2))
v_result3.set(round(float(v_result1.get() + v_result2.get()), 2))
e_receita1.delete(0, END)
e_receita2.delete(0, END)
# ---
bt = Button(root, text='Calcular', command=calc)
bt.place(x=10, y=180)
# ---
root.mainloop()
You can bind to the "." character and have it insert a "," instead. Use return "break" to prevent the default behavior.
def replace_period(event):
event.widget.insert("insert", ",")
return "break"
e_receita1.bind("<.>", replace_period) # or "<period>"
Using a bind, and in the callback function replacing "." with ",":
from tkinter import *
# ---
root = Tk()
root.geometry('350x350')
# ---
def callback(e):
"""Function to change "." to "," while typing in an entry"""
val = e.widget.get()
# If statement avoids unnecessary delete/insert calls
if "." in val:
e.widget.delete(0, "end")
e.widget.insert(0, val.replace(".", ","))
l_receita1 = Label(root, text='Receita 1')
l_receita1.place(x=10, y=10)
e_receita1 = Entry(root)
e_receita1.bind('<KeyRelease>', callback) # Bind the key release
e_receita1.place(x=100, y=10)
l_receita2 = Label(root, text='Receita 2')
l_receita2.place(x=10, y=40)
e_receita2 = Entry(root)
e_receita2.bind('<KeyRelease>', callback) # Bind the key release
e_receita2.place(x=100, y=40)
# ---
v_result1 = DoubleVar()
l_resRec1 = Label(root, textvariable=v_result1)
l_resRec1.place(x=10, y=100)
v_result2 = DoubleVar()
l_resRec2 = Label(root, textvariable=v_result2)
l_resRec2.place(x=10, y=140)
v_result3 = DoubleVar()
l_resRec3 = Label(root, textvariable=v_result3)
l_resRec3.place(x=10, y=220)
# ---
def calc():
v_result1.set(round(float(e_receita1.get().replace(",", ".")) * 8 / 100, 2))
v_result2.set(round(float(e_receita2.get().replace(",", ".")) * 12 / 100, 2))
v_result3.set(round(float(v_result1.get() + v_result2.get()), 2))
e_receita1.delete(0, END)
e_receita2.delete(0, END)
# ---
bt = Button(root, text='Calcular', command=calc)
bt.place(x=10, y=180)
# ---
root.mainloop()

Python Pound to Kilogram

I need help displaying "cannot convert negatives" in tkinter.
I want it to say "cannot convert negatives" when I type in a negative number.
Code:
from tkinter import *
def convert():
P = float(pound.get())
K = P * 0.453592
Kilogram.set(str(K))
input (P)
if (P) < 0:
print("cannot convert negitaves") # i need to display this when i run the program
else:
K = P * 0.453592
print(K)
my_window = Tk()
Kilogram = StringVar()
pound = StringVar()
label_1 = Label(my_window, text="Enter the pound")
label_2 = Label(my_window, text="Kilogram")
display_kilogram_label = Label(my_window, textvariable=Kilogram)
pound_entry = Entry(my_window, textvariable=pound)
convert_button = Button(my_window, text="Convert", command=convert)
label_1.grid(row=0, column=0)
pound_entry.grid(row=0, column=1)
label_2.grid(row=1, column=0)
display_kilogram_label.grid(row=1, column=1)
convert_button.grid(row=2, column=0)
my_window.mainloop()
I commented out the "input (P)" line, and refactored your convert function a little bit, now it works:
def convert():
P = float(pound.get())
# input (P)
if P < 0:
print("cannot convert negitaves") # i need to display this when i run the program
else:
K = P * 0.453592
Kilogram.set(str(K))
print(K)
Based on your feedback, I changed the convert function to display the error message as well:
def convert():
P = float(pound.get())
if P < 0:
Kilogram.set("Cannot convert negatives!")
else:
Kilogram.set(str(P * 0.453592))
Simply commenting the input(P) line is what you need to do to make your program run.
from tkinter import *
def convert():
P = float(pound.get())
K = P * 0.453592
Kilogram.set(str(K))
if (P) < 0:
print("cannot convert negitaves") # i need to display this when i run the program
else:
K = P * 0.453592
print(K)
my_window = Tk()
Kilogram = StringVar()
pound = StringVar()
label_1 = Label(my_window, text="Enter the pound")
label_2 = Label(my_window, text="Kilogram")
display_kilogram_label = Label(my_window, textvariable=Kilogram)
pound_entry = Entry(my_window, textvariable=pound)
convert_button = Button(my_window, text="Convert", command=convert)
label_1.grid(row=0, column=0)
pound_entry.grid(row=0, column=1)
label_2.grid(row=1, column=0)
display_kilogram_label.grid(row=1, column=1)
convert_button.grid(row=2, column=0)
my_window.mainloop()

Categories

Resources