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

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()

Related

how can I print the return value of a function to entry in tinker?

from tkinter import *
def c_to_f(celsius):
return str(float(celsius) * 1.8 + 32)
window = Tk()
f = Label(window, text="ºF")
f.pack()
finpt = Entry(window)
fvalue = finpt.get()
finpt.pack()
c = Label(window, text="ºC")
c.pack()
cinpt = Entry(window)
cvalue = cinpt.get()
cinpt.pack()
to_f = Button(window, text="Nach ºF umrechnen", command=finpt.insert(0, f"{c_to_f(cvalue)}"))
to_f.pack()
window.mainloop()
After pressing the button, I want to return the show the result of c_to_f(cvalue) in Label c. How can I manage that?
It is better to create another function for the button to_f and do the conversion and show result inside that function:
from tkinter import *
def c_to_f(celsius):
return str(float(celsius) * 1.8 + 32)
def convert_to_fahrenheit():
try:
f = c_to_f(cinpt.get())
finpt.delete(0, END)
finpt.insert(END, f)
except ValueError as ex:
print(ex)
window = Tk()
f = Label(window, text="ºF")
f.pack()
finpt = Entry(window)
#fvalue = finpt.get()
finpt.pack()
c = Label(window, text="ºC")
c.pack()
cinpt = Entry(window)
#cvalue = cinpt.get()
cinpt.pack()
to_f = Button(window, text="Nach ºF umrechnen", command=convert_to_fahrenheit)
to_f.pack()
window.mainloop()
Your code is giving too much problem.
Try this:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title('Temperature Converter')
root.geometry('300x70')
root.resizable(False, False)
def fahrenheit_to_celsius(f):
""" Convert fahrenheit to celsius
"""
return (f - 32) * 5/9
frame = ttk.Frame(root)
options = {'padx': 5, 'pady': 5}
temperature_label = ttk.Label(frame, text='Fahrenheit')
temperature_label.grid(column=0, row=0, sticky='W', **options)
temperature = tk.StringVar()
temperature_entry = ttk.Entry(frame, textvariable=temperature)
temperature_entry.grid(column=1, row=0, **options)
temperature_entry.focus()
def convert_button_clicked():
f = float(temperature.get())
c = fahrenheit_to_celsius(f)
result = f'{f} Fahrenheit = {c:.2f} Celsius'
result_label.config(text=result)
convert_button = ttk.Button(frame, text='Convert')
convert_button.grid(column=2, row=0, sticky='W', **options)
convert_button.configure(command=convert_button_clicked)
result_label = ttk.Label(frame)
result_label.grid(row=1, columnspan=3, **options)
frame.grid(padx=10, pady=10)
root.mainloop()
Screenshot:

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')

Python/Tkinter -

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()

How can I pop up a messagebox from a menu?

I am a newbie in Python. I want to create a program with Tkinter that takes the entry from the entry "box" and then compares each character of it with the charset and finally pops up a messagebox that shows the phrase. I have almost complete it but I can not make this line work:
info_menu.add_command(label="About",
command=messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017")
Full code:
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
import string as s
class Bruteforcer:
def output(self, result):
self.result = result
if result == "":
messagebox.showwarning(title="Enter a Phrase",
message="Please enter a Phrase!")
else:
messagebox.showinfo(title="Phrase Found!",
message=("The process completed Successfully!\n The Phrase Found!!!!\n", result))
def submit_button_pressed(self):
entry_val = self.entry_value.get()
charset = list(s.ascii_letters + "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψω" + s.digits + s.punctuation)
result = ""
x = 0
while x <= len(entry_val)-1:
echar = entry_val[x]
for char in charset:
if char == echar:
result += echar
x += 1
break
return self.output(result)
def __init__(self, root):
self.entry_value = StringVar(root, "")
self.the_menu = Menu(root)
info_menu = Menu(self.the_menu, tearoff=0)
**info_menu.add_command(label="About",
command=messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017")**
)
info_menu.add_separator()
info_menu.add_command(label="Quit", command=root.quit)
self.the_menu.add_cascade(label="Info", menu=info_menu)
root.config(menu=self.the_menu)
text_fond = StringVar()
text_fond.set("Times")
root.title("Graphical Bruteforcer")
root.geometry("500x500")
root.resizable(width=False, height=False)
style = ttk.Style()
style.configure("TButton",
foreground="red",
fond="Times 20",
padding=10)
style.configure("TEntry",
foreground="red",
fond="Times 20",
padding=10)
style.configure("TLabel",
foreground="red",
fond="Times 35 Bold")
# ---------- Entry -----------
self.entry_value = ttk.Entry(root,
textvariable=self.entry_value, width=25, state="normal")
self.entry_value.grid(row=1, columnspan=2)
# ---------- Label ----------
self.secret_label = ttk.Label(root,
text="The Secret Phrase").grid(row=0, column=0)
# ---------- Button ---------
self.button_submit = ttk.Button(root,
text="Submit", command=self.submit_button_pressed)
self.button_submit.grid(row=1, column=2)
root = Tk()
brute = Bruteforcer(root)
root.mainloop()
As furas said in the comments, command= expects a function. So you should replace
info_menu.add_command(label="About",
command=messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017"))
by something like
def show_about():
''' show the about messagebox '''
messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017")
info_menu.add_command(label="About", command=show_about)

How to get tkinter Spinbox's value?

I am trying to make a timer on python Tkinter. To set the timer, I am using spinboxes. But, I am having trouble getting the value of my spinboxes to be turned into the variables time_h, time_m and time_s.
I have tried .get() but it is not working. When I tried printing the variables I got NameError: name 'spin_h' is not defined.
from tkinter import *
window = Tk()
window.title("Timer")
window.geometry('350x200')
hour = 0
minute = 0
second = 0
timer = (str(hour) + ':' + str(minute) + ':' + str(second))
lbl = Label(window, text=timer, font=("Arial Bold", 50))
hour_s = 0
min_s = 0
sec_s = 0
def save_time():
time_h = spin_h.get()
time_m = spin_m.get()
time_s = spin_s.get()
def new_window():
set_time = Tk()
spin_h = Spinbox(set_time, from_=0, to=10, width=5)
spin_h.grid(column=1,row=0)
spin_m = Spinbox(set_time, from_=0, to=60, width=5)
spin_m.grid(column=3,row=0)
spin_s = Spinbox(set_time, from_=0, to=60, width=5)
spin_s.grid(column=5,row=0)
h_label = Label(set_time, text='h', font=("Arial Bold", 10))
h_label.grid(column=2, row=0)
m_label = Label(set_time, text='m', font=("Arial Bold", 10))
m_label.grid(column=4, row=0)
s_label = Label(set_time, text='s', font=("Arial Bold", 10))
s_label.grid(column=6, row=0)
set_button = Button(set_time, text="Set Time", command=save_time)
set_button.grid(column=3, row=2)
btn = Button(window, text="Set Time", command=new_window)
btn.grid(column=3, row=2)
lbl.grid(column=3, row=0)
window.mainloop()
spin_h is a variable local to the new_window() function and there cannot be accessed by the save_time() function. You could declare it a global variable at the beginning of new_window() to fix that. - #Martineau (just made it into an answer instead of a comment).
Thanks Martineau

Categories

Resources