How to get the user to enter a float in entry box? - python

If I create an entry box like so:
myentry = Entry ()
myentry.place (x = 54,y = 104)
the value that the user enters is a string value. What do I have to add so that the entry is a float? I have tried to write "float" in the parentheses beside Entry but it didn't work and showed me an error saying that tk() does not support float. Any help would be appreciated!

I wrote a simple script to demonstrate how to do what you want:
from Tkinter import Tk, Button, Entry, END
root = Tk()
def click():
"""Handle button click"""
# Get the input
val = myentry.get()
try:
# Try to make it a float
val = float(val)
print val
except ValueError:
# Print this if the input cannot be made a float
print "Bad input"
# Clear the entrybox
myentry.delete(0, END)
# Made this to demonstrate
Button(text="Print input", command=click).grid()
myentry = Entry()
myentry.grid()
root.mainloop()
When you click the button, the program tries to make the text in the entrybox a float. If it can't, it prints "Bad input". Otherwise, it prints the float in the terminal.

Related

Allowing only a range of inputs within an entry field in Tkinter

I need to implement an entry box that accepts only a range of DoubleVar values. I have referenced this question that was asked How to only allow certain parameters within an entry field on Tkinter, but I want the user to be notified (using a change in font colour or anything) while they are entering the values. I've read the documentation but this is something that I haven't come across.
I'm new to Tkinter, so please excuse me if this sounds very stupid
You can bind KeyRelease event of the Entry to a callback and check whether the input value is valid and within the required range, then update the foreground color of the Entry accordingly:
import tkinter as tk
root = tk.Tk()
def check_value(entry, min_value, max_value):
try:
value = float(entry.get().strip())
valid = min_value <= value <= max_value
except ValueError:
valid = False
entry.config(fg='black' if valid else 'red')
return valid # in case you want the checking result somewhere else
entry = tk.Entry(root)
entry.pack()
entry.bind('<KeyRelease>', lambda e: check_value(e.widget, 10, 20))
root.mainloop()
Use the validatecommand option for the Entry.
Some code fragments to show how it works:
root = tk.Tk()
vcmd = root.register(is_number)
e = ttk.Entry(pressf, justify='right', validate='key', validatecommand=(vcmd, '%P'))
def is_number(data):
"""Validate the contents of an entry widget as a float."""
if data == '':
return True
try:
rv = float(data)
if rv < 0:
return False
except ValueError:
return False
return True
This basically calls the validation function on every keypress. Only if the validation succeeds is the character added to the entry.
You can find a complete working example here.
Edit
Above is the "canonical" example of a validator. It allows or disallows characters into the Entry.
But you can also use it in other ways.
For example, you can always return True, but e.g. change the text color of the Entry to red if the value is not within the limits you want.

Button error, but I get IndexError: list index out of range

I have two buttons on my interface. I want both of them to be able to call their respective functions when I either click on them or a hit the Enter Key.
The problem I'm having is that only the last button in the traveral focus gets activated when I hit the Enter Key, even if the preceeding one has the focus. What can I do to resolve this problem.
Useful answer are welcome and appreciated.
This is the problem in question:
from tkinter import *
w = Tk()
def startProgram(event = None):
print('Program Starting')
def readyContent(event = None):
print('Content being prepared')
# Buttons
Button(text='Prepare', command=readyContent).grid(row=10,column=2)
w.bind('<Return>',readyContent) # Binds the Return key to a Function
Button(text='Start', command=startProgram).grid(row=10,column=3)
w.bind('<Return>',startProgram) # Binds the Return key to a Function
w.mainloop()
When you click on the Prepare or Start button, in return you get either Content being prepared or Program Starting repectively. Nothing like that happens when you use the Tab Key to give focus to one button or the other. Even if the focus is on the Prepare button, when you hit Enter you get: Program Starting
This is the solution to my problem.
I hope it helps anyone else having the same problem as me.
from tkinter import *
w = Tk()
def startProgram(event = None):
print('Program Starting')
def readyContent(event = None):
print('Content being prepared')
# Buttons
btn1 = Button(text='Prepare', command=readyContent)
btn1.grid(row=10,column=2)
btn1.bind('<Return>',readyContent) # Binds the Return key to a Function
btn2 = Button(text='Start', command=startProgram)
btn2.grid(row=10,column=3)
btn2.bind('<Return>',startProgram) # Binds the Return key to a Function
w.mainloop()
Have a good day! :)

What caused the error

I am trying to make GUI that reverses the user input but something is wrong
from tkinter import *
from tkinter.ttk import *
def reverse(s):
s=U.get()
return s[::-1]
root=Tk(className="Reverse your text")
la=Label(root, text="Enter text to reverse")
la.pack()
U=Entry(root,textvariable=s)
U.pack()
BT=Button(root, text="reverse", command=reverse(s))
BT.pack()
root.mainloop()
Error: U=Entry(root,textvariable=s)
NameError: name 's' is not defined
def reverse(s): should not have an s if you don't intend to pass any arguments to the function. Likewise for command=reverse(s)
U=Entry(root,textvariable=s) does not need a textvariable if you're just going to access the Entry's value directly with .get. And anyway, you can't use s here, because you never assigned a StringVar object to s to begin with.
The value returned by return s[::-1] will not be visible in any way to the user. If you want to show the reversed string, you need to print it or insert it into the entry, or similar.
from tkinter import *
from tkinter.ttk import *
def reverse():
s=U.get()
U.delete(0, END)
U.insert(0,s[::-1])
root=Tk(className="Reverse your text")
la=Label(root, text="Enter text to reverse")
la.pack()
U=Entry(root)
U.pack()
BT=Button(root, text="reverse", command=reverse)
BT.pack()
root.mainloop()
Result:

How to make expressions in Tkinter Python

I'm new in python programming and I'm having some issues in developing a specific part of my GUI with Tkinter.
What I'm trying to do is, a space where the user could enter (type) his math equation and the software make the calculation with the variables previously calculated.
I've found a lot of calculators for Tkinter, but none of then is what I'm looking for. And I don't have much experience with classes definitions.
I made this simple layout to explain better what I want to do:
import tkinter as tk
root = tk.Tk()
Iflabel = tk.Label(root, text = "If...")
Iflabel.pack()
IfEntry = tk.Entry(root)
IfEntry.pack()
thenlabel = tk.Label(root, text = "Then...")
thenEntry = tk.Entry(root)
thenlabel.pack()
thenEntry.pack()
elselabel = tk.Label(root, text = "else..")
elseEntry = tk.Entry(root)
elselabel.pack()
elseEntry.pack()
applybutton = tk.Button(root, text = "Calculate")
applybutton.pack()
root.mainloop()
This simple code for Python 3 have 3 Entry spaces
1st) If...
2nd Then...
3rd) Else...
So, the user will enter with his conditional expression and the software will do the job. In my mind, another important thing is if the user left the "if" space in blank, he will just type his expression inside "Then..." Entry and press the button "calculate" or build all expression with the statements.
If someone could give some ideas about how and what to do....
(without classes, if it is possible)
I'l give some situations for exemplification
1st using statements:
var = the variable previously calculated and stored in the script
out = output
if var >= 10
then out = 4
else out = 2
2nd Without using statement the user will type in "Then" Entry the expression that he want to calculate and that would be:
Then: Out = (((var)**2) +(2*var))**(1/2)
Again, it's just for exemplification...I don't need this specific layout. If anyone has an idea how to construct it better, is welcome.
Thanks all.
Here is a simple version of what you are trying to do.
We need to use the eval built in function to evaluate the math of a string.
We should also write our code with some error handling as there is a very good change a user will type a formula wrong and the eval statement will fail.
For more information on eval and exec take a look at this post here. I think it does a good job of explaining the two.
Here is what it would look like:
import tkinter as tk
root = tk.Tk()
math_label = tk.Label(root, text = "Type formula and press the Calculate button.")
math_label.pack()
math_entry = tk.Entry(root)
math_entry.pack()
result_label = tk.Label(root, text = "Results: ")
result_label.pack(side = "bottom")
def perform_calc():
global result_label
try:
result = eval(math_entry.get())
result_label.config(text = "Results: {}".format(result))
except:
result_label.config(text = "Bad formula, try again.")
applybutton = tk.Button(root, text = "Calculate", command = perform_calc)
applybutton.pack()
root.mainloop()
The first answer gets at the right thought, but it can also be matched a little more explicitly to the example you gave, in case you want to take this a little further.
Basically you want to use the eval statement to test your conditional, and then use the exec statement to run your python code blocks. You have to pass in the globals() argument in order to make sure your exec functions modify the correct variables in this case
See below:
import tkinter as tk
from tkinter import messagebox
var = 10
out = 0
def calculate():
global out
try:
if eval(IfEntry.get()):
exec(thenEntry.get(), globals())
else:
exec(elseEntry.get(), globals())
messagebox.showinfo(title="Calculation", message="out: " + str(out))
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
msg = traceback.format_exception(exc_type, exc_value, exc_traceback)
messagebox.showinfo("Bad Entry", message=msg)
root = tk.Tk()
Iflabel = tk.Label(root, text = "If...")
Iflabel.pack()
IfEntry = tk.Entry(root)
IfEntry.insert(0, "var >= 10")
IfEntry.pack()
thenlabel = tk.Label(root, text = "Then...")
thenEntry = tk.Entry(root)
thenlabel.pack()
thenEntry.insert(0, "out = 4")
thenEntry.pack()
elselabel = tk.Label(root, text = "else..")
elseEntry = tk.Entry(root)
elselabel.pack()
elseEntry.insert(0, "out = 2")
elseEntry.pack()
applybutton = tk.Button(root, command=calculate, text = "Calculate")
applybutton.pack()
applybutton.focus_displayof
root.mainloop()

Python 3.3 GUI Program

Celsius to Fahrenheit-- Write a GUI program that converts Celsius temperatures to Fahrenheit temperatures. The user should be able to enter a Celsius temperature, click a button, and then see the equivalent Fahrenheit temperature. Use the following formula to make the conversion:
F = 9/5C +32
F is the Fahrenheit temperature and C is the Celsius temperature.
THIS IS THE CODE I HAVE SO FAR, THE ERROR I GET says "invalid literal for int() with base 10: ''" I need help getting it to run correctly.
#import
#main function
from tkinter import *
def main():
root=Tk()
root.title("Some GUI")
root.geometry("400x700")
#someothersting=""
someotherstring=""
#enter Celcius
L1=Label(root,text="Enter a Celcius temperature.")
E1=Entry(root,textvariable=someotherstring)
somebutton=Button(root, text="Total", command=convert(someotherstring))
somebutton.pack()
E1.pack()
L1.pack()
root.mainloop()#main loop
#convert Celcius to Fahrenheit
def convert(somestring):
thestring=""
thestring=somestring
cel=0
far=0
cel=int(thestring)
far=(9/5*(cel))+32
print(far)
Your main problem is this line;
somebutton=Button(root, text="Total", command=convert(someotherstring))
...which will call convert(someotherstring) immediately and assign the result to command. Since someotherstring is empty when this line is reached, it will fail to convert the value and fail the program.
If you don't want it evaluated immediately but instead on button press, you can use a lambda as a command;
somebutton=Button(root, text="Total", command=lambda: convert(E1.get()))
...which will eliminate the use of someotherstring completely and just call convert with the contents of E1 when the button is clicked.
This could be due to int("")
In main(), do
def main():
# ...
someotherstring = 0 # Since its trying to get int
Or you can check if its empty in convert():
def convert(somestring):
if somestring != "":
# cel=0 dont need these in python
# far=0
cel=int(somestring)
far=(9/5*(cel))+32
print(far)
Note: Check if you are using someotherstring properly with Entry widget. I believe you are supposed to use StringVar() and do stringvar.get() to get the text inside widget.

Categories