How to make entries from an entry widget interact with each other - python

I'm trying to make a program which would allow a user to enter a currency and a US Dollar amount, and have the program run the conversion, and of course show the result to the user. I'm using tkinter and have a gui pop up where the user can enter in values, and as of now it just prints whatever the user entered on the IDLE window (to test whether what I have would do anything).
from tkinter import *
from math import *
fields = 'Dollars' , 'Currency'
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
def makeform(root, fields):
entries = []
for field in fields:
row = Frame(root)
lab = Label(row, width = 15, text = field, anchor = 'w')
ent = Entry(row)
row.pack(side = TOP, fill = X, padx=5, pady = 5)
lab.pack(side = LEFT)
ent.pack(side = RIGHT, expand = YES, fill = X)
entries.append((field, ent))
return entries
if __name__ == '__main__':
root = Tk()
ents = makeform(root, fields)
root.bind('<Return>', (lambda event, e = ents: fetch(e)))
b1 = Button(root, text = 'Show', command = (lambda e=ents: fetch(e)))
b1.pack(side = LEFT, padx = 5, pady =5)
b2 = Button(root, text = 'Quit', command=root.quit)
b2.pack(side = LEFT, padx = 5, pady = 5)
root.mainloop()
The only code that I have used for converting currency is something like this:
def convert():
option = input("Please enter what you would like to convert $ to; Yen, Euros, or Pesos: ")
dollars = eval(input("Please enter the dollar amount you wish to convert: "))
if dollars < 0:
print("You must enter a value greater than 0.")
convert()
elif option == "Yen":
print("The amount of Yen you have is: ", dollars * 106.84)
elif option == "Euros":
print("The amount of Euros you have is: ", dollars * 0.77)
elif option == "Pesos":
print("The amount of Pesos you have is: ", dollars * 13.38)
I've looked across numerous websites, but I have not found any useful information anywhere on how to incorporate the two together. If anyone could help me understand what I need to do, it would be greatly appreciated.

Rephrasing the question: How to update the value of on Entry depending on the value of another Entry?
This seems to require code like:
value=eval(entryDollar.get())
entryCurrency.delete(0,END)
entryCurrency.insert(0,repr(value*exchangeRate))
In your current bindings with Show, <Return> it is unclear what direction you want to convert; a direction indicator might help.

Related

Change (update) text in Python Tkinter widgets

I am trying to update information in tkinter labels and buttons without redrawing entire screens. I'm using Python 3, a Raspberry Pi, and Idle. I have a trivial example of what I am trying to do. I see comments here that suggest I need to learn to manipulate stringvariable or IntVar, etc. but my book is totally unhelpful in that regard. In this example, I would like the number between the buttons to track the value of the number as it changes with button pushes.
##MoreOrLess.01.py
from tkinter import *
global number
number = 5
root = Tk()
root.title("Test Buttons")
def Less():
global number
number -= 1
print ("The number is now ", number)
def More():
global number
number += 1
print("The number is now ", number)
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, text = number).pack(pady = 20)
MakeLabel(number)
Not only do you base yourself in a book, check the official documentation of tkinter. in your case you must create a variable of type IntVar with its set() and get() method, and when you want to link that variable through textvariable.
from tkinter import *
root = Tk()
root.title("Test Buttons")
number = IntVar()
number.set(5)
def Less():
number.set(number.get() - 1)
print ("The number is now ", number.get())
def More():
number.set(number.get() + 1)
print("The number is now ", number.get())
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, textvariable = number).pack(pady = 20)
MakeLabel(number)
root.mainloop()

Python Prints List Object [tkinter.StringVar object at 0x01FEAD50], But Not Items in List *Tkinter*

I am trying to create a GUI that will be able to monitor the integrity of files using their MD5 hashes (the actual monitoring of updates log can be in the command prompt).
I got the initial command line program to work perfectly, but am having an issue when converting it to a GUI based version using tkinter.
I use the GUI to create a list of files that I want to monitor in the 'addFiles' function, but when I try to pass that list to the 'checkForIntegrity' function (or print the list with my test print(listOfFiles) code in that function), all I get is [tkinter.StringVar object at 0x01FEAD50], but do not get the actual list.
I have searched far and wide for an answer and have tried using various implementations of 'listOfFiles.get()' in different locations but have had no success.
I have no idea why I only get the actual list object but no listed items, my code is below.
Thank you in advance everyone.
edit: Just to be clear, my 'GUI()' function creates a window that asks how many files the user would like to monitor and passes that to the 'addFiles()' function which allows input for the amount of files they specify. I need to be able to pass the files they specify in that GUI to the program via a list. Thanks again.
import hashlib
import time
from tkinter import *
def main():
GUI()
def GUI():
window = Tk()
window.title("Integrity Checker")
frame1 = Frame(window)
frame1.pack()
label1 = Label(frame1, text = "***Proof Of Concept Program That Monitors the Integriry of Files***")
label1.grid(row = 1, column = 1)
frame2 = Frame(window)
frame2.pack()
getNumberOfFiles = Label(frame2, text = "Insert Number of Files You Would Like to Check: ")
getNumberOfFiles.grid(row = 2, column = 1)
numberOfFiles = IntVar()
NumberOfFilesOption = Entry(frame2, textvariable = numberOfFiles)
NumberOfFilesOption.grid(row = 2, column = 2)
button = Button(frame2, text = "OK", command = lambda : addFiles(numberOfFiles))
button.grid(row = 2, column = 3)
window.mainloop()
def addFiles(numberOfFiles):
listOfFiles = []
window = Tk()
window.title("Add Files")
frame1 = Frame(window)
frame1.pack()
label1 = Label(frame1, text = "***Select The Files You Want To Monitor***")
label1.grid(row = 1, column = 1)
for i in range (numberOfFiles.get()):
AddFile = Label(frame1, text = "Add File:")
AddFile.grid(row = (i + 3), column = 1)
FileName = StringVar()
FileNameOption = Entry(frame1, textvariable = FileName)
FileNameOption.grid(row = (i + 3), column = 2)
button = Button(frame1, text = "OK", command = lambda : listOfFiles.append(FileName))
button.grid(row = (i + 3), column = 3)
button2 = Button(frame1, text = "Done", command = lambda : checkforINTEGRITY(numberOfFiles, listOfFiles))
button2.grid(row = (i + 4), column = 2)
window.mainloop()
def checkforINTEGRITY(numberOfFiles, listOfFiles):
#Number = numberOfFiles.get()
#listOfFiles = []
#count = 0
#numberOfFiles = eval(input("How many files would you like to monitor?: "))
#while count < Number:
# filename = input("Enter the name of the file you would like to check: ")
# count += 1
# listOfFiles.append(filename)
print(listOfFiles)
i = 0
originalList = []
for file in listOfFiles:
original_md5 = hashlib.md5(open(listOfFiles[i],'rb').read()).hexdigest()
originalList.append(original_md5)
i += 1
print(originalList)
while True:
i = 0
while i < Number:
md5_returned = hashlib.md5(open(listOfFiles[i],'rb').read()).hexdigest()
print(md5_returned)
if originalList[i] == md5_returned:
print("The file", listOfFiles[i], "has not changed")
else:
print("The file", listOfFiles[i], "has been modified!")
i += 1
time.sleep(5)
main()
It looks like you want to call the get method on FileNameOption:
button = Button(frame1, text = "OK", command = lambda : listOfFiles.append(FileNameOption.get()))
With this change I was able to get a list of strings in listOfFiles.

How to update a label in Tkinter, StringVar() not working

I am working on this short code that compares the single characters of two strings. After the first running, when I change the strings in the entryBoxes,I would like to replace the label created before, instead of creating a new one. I have already tried with StringVar() but it seems not working. (If it can be useful I'm using Python 2.7.6). Could you please give me a hint?
from Tkinter import *
app = Tk()
app.geometry('450x300')
labelTF = Label(app, text="Insert sequence of TF").pack()
eTF = Entry(app, width=50)
eTF.pack()
eTF.focus_set()
labelSpazio = Label(app, text="\n").pack()
labelResultedSequence = Label(app, text="Insert sequence of ResultedSequence").pack()
eResultedSequence = Entry(app, width=50)
eResultedSequence.pack()
eResultedSequence.focus_set()
def prova():
count = 0
uno = eTF.get().lower()
due = eResultedSequence.get().lower()
if len(uno)==len(due):
for i in range(0,len(uno)):
if uno[i] == due[i]:
if uno[i] in ("a", "c","g","t"):
count = count + 1
if uno[i] == "r" and due[i] in ("a", "g"):
count = count + 1
if uno[i] == "y" and due[i] in ("t", "c"):
count = count + 1
percentage = int(float(count)/float(len(uno))*100)
labelSpazio = Label(app, text="\n").pack()
mlabel3=Label(app,text= "The final similarity percentage is: "+(str(percentage) + " %")).pack()
if len(uno)!=len(due):
mlabel2 = Label(app,text="The length of the sequences should be the same").pack()
b = Button(app, text="get", width=10, command=prova)
b.pack()
mainloop()
Create the labels only once outside of the for loop and use a StringVar to modify its value. It would look like this:
# initialization
app = Tk()
label3text = StringVar()
mlabel3 = Label(app, textvariable=label3text, width=100)
mlabel3.pack()
Then in the for loop inside your function:
label3text.set("The final similarity percentage is: "+(str(percentage) + " %"))

Tip calculator - syntax error

Hello guys im new to programming relatively, but all the same im trying to use a GUI interface to build a tip calculator. nothing big, nothing relatively hard, but im running into errors. for some reason my Python wont show the errors. it just goes to the shell, says SyntaxError: and then quits back to the script. it used to show the errors but i dont know whats wrong... anyways if you guys could help me troubleshoot this id greatly appreciate it..
`
# A tip calculator
# A tip calculator using a GUI interface
# Austin Howard Aug - 13 - 2014
from tkinter import *
#Creating buttons.
class Calculator(Frame):
""" A GUI tip calculator."""
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.creating_buttons()
def creating_buttons(self):
"""This list includes Entry fields, which the user will use to define
several objects such as Bill, and how many people are paying on that bill."""
#Create an entry field button for how much the bill total is.
#Create a label
bill_lbl = Label(self,
text = "Bill: ")
bill_lbl.grid(row = 1,
column = 0,
columnspan = 1,
sticky = W)
#Create an Entry field.
bill_ent = Entry(self)
bill_ent.grid(row = 1,
column = 1,
sticky = W)
#Create a Button for how many people will be paying on the bill
#Create label
people_paying_lbl = Label(self,
text = "How many people are paying on this bill?: ")
people_paying_lbl.grid(row = 2,
column = 0,
columnspan = 1,
sticky = W)
#Create an entry field
people_paying_ent = Entry(self)
people_paying_ent.grid(row = 2,
column = 1,
sticky = W)
#Create a text box to display the totals in
bill_total_txt = Text(self,
width = 40,
height = 40,
wrap = WORD)
bill_total_txt.grid(row = 3,
column = 0,
columnspan = 2,
sticky = W)
#Create a Submit button
submit = Button(self,
text = "Submit",
command = self.total)
submit.grid(row = 4,
column = 0,
sticky = W)
def total(self):
""" Takes the values from Bill, and # of people to get the amount that will be
displayed in the text box."""
TAX = .15
bill = float(bill_ent)
people = people_paying_ent
Total = ("The tip is: $", TAX * bill, "\nThe total for the bill is: $",
TAX * bill + bill,
"divided among the people paying equally is: $",
TAX * bill + bill / people "per, person.")
bill_total_txt.delete(0.0, END)
bill_total_txt.insert(0.0, Total)
#Starting the Program
root = Tk()
root.title("Tip Calculator")
app = Calculator(root)
root.mainloop()
`
You have an error on line 68:
Replace
TAX * bill + bill / people "per, person.")
with
TAX * bill + bill / people, "per, person.")
Also make sure you remove the backtick after root.mainloop()
Your way of getting the input from the Entry boxes is wrong. You should bind a StringVariable to them, to later be able to get what the user typed:
self.billvar = StringVar()
bill_ent = Entry(self, textvariable = self.billvar)
And the same for the number of people box.
Then in your total function you can read the values by using self.billvar.get(). You can convert this to a float using float(self.billvar.get()). However, when this fails (the user typed in something that can not be converted to a float) you probably want to tell them instead of having the program throwing an error. So you should use something like:
try:
convert input
except:
what to do if it fails, tell the user?
else:
what to do if it did not fail, so do the calculations
Your program then becomes something like this (I made comments with ##):
# A tip calculator
# A tip calculator using a GUI interface
# Austin Howard Aug - 13 - 2014
from tkinter import *
#Creating buttons.
class Calculator(Frame):
""" A GUI tip calculator."""
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.creating_buttons()
def creating_buttons(self):
"""This list includes Entry fields, which the user will use to define
several objects such as Bill, and how many people are paying on that bill."""
#Create an entry field button for how much the bill total is.
#Create a label
bill_lbl = Label(self,
text = "Bill: ")
bill_lbl.grid(row = 1,
column = 0,
columnspan = 1,
sticky = W)
#Create an Entry field.
## Create a StringVar and link it to the entry box
self.billvar = StringVar()
bill_ent = Entry(self, textvariable = self.billvar)
bill_ent.grid(row = 1,
column = 1,
sticky = W)
#Create a Button for how many people will be paying on the bill
#Create label
people_paying_lbl = Label(self,
text = "How many people are paying on this bill?: ")
people_paying_lbl.grid(row = 2,
column = 0,
columnspan = 1,
sticky = W)
#Create an entry field
## Create a StringVar and link it to the entry box
self.pplvar = StringVar()
people_paying_ent = Entry(self, textvariable = self.pplvar)
people_paying_ent.grid(row = 2,
column = 1,
sticky = W)
#Create a text box to display the totals in
## This had to be self.bill_total_txt, to be able to put text in it from the total function
self.bill_total_txt = Text(self,
height = 10,
width = 40,
wrap = WORD)
self.bill_total_txt.grid(row = 3,
column = 0,
columnspan = 2,
sticky = W)
#Create a Submit button
submit = Button(self,
text = "Submit",
command = self.total)
submit.grid(row = 4,
column = 0,
sticky = W)
def total(self):
""" Takes the values from Bill, and # of people to get the amount that will be
displayed in the text box."""
TAX = .15
## Try to convert the bill to a float and the number of people to an integer
try:
bill = float(self.billvar.get())
people = int(self.pplvar.get())
## If something goes wrong tell the user the input is invalid
except:
self.bill_total_txt.delete(0.0, END)
self.bill_total_txt.insert(0.0, 'Invalid input')
## If the conversion was possible, calculate the tip, the total amount and the amout per person and format them as a string with two decimals
## Then create the complete message as a list and join it togeather when writing it to the textbox
else:
tip = "%.2f" % (TAX * bill)
tot = "%.2f" % (TAX * bill + bill)
tot_pp = "%.2f" % ((TAX * bill + bill) / people)
Total = ["The tip is: $", tip,
"\nThe total for the bill is: $",
tot,
" divided among the people paying equally is: $",
tot_pp,
" per person."]
self.bill_total_txt.delete(0.0, END)
self.bill_total_txt.insert(0.0, ''.join(Total))
#Starting the Program
root = Tk()
root.title("Tip Calculator")
app = Calculator(root)
root.mainloop()

Tkinter ISBN Converter Need a way of printing results on Tkinter page

import sys
from tkinter import *
def main():
mtext = ment.get()
mlabel2 = Label(top, text=mtext).pack()
def isbn():
digits = [(11 - i) * num for i, num in enumerate(map(int, list()))]
digit_11 = 11 - (sum(digits) % 11)
if digit_11 == 10:
digit_11 = 'X'
digits.append(digit_11)
isbn_number = "".join(map(str, digits))
label2 = Label(top, text = "Your ISBN number is",).pack()
top = Tk()
top.geometry("450x450+500+300")
top.title("Test")
button = Button(top,text="OK", command = isbn, fg = "red", bg="blue").pack()
label = Label(top, text = "Please enter the 10 digit number").pack()
ment= IntVar()
mEntry = Entry(top,textvariable=ment).pack()
Hello, I the code at the moment is a working stage, I just need a way of the results printing because at the moment it is not. I would also like the converter to work proper ally with 10 digits and the 11th digit being the number that the converter finds outs. Thanls
Note how the button's command calls the function to perform your operation:
from tkinter import *
def find_isbn(isbn, lbl):
if len(isbn) == 10:
mult = 11
total = 0
for i in range(len(isbn)):
total += int(isbn[i]) * mult
mult -= 1
digit_11 = 11 - (total % 11)
if digit_11 == 10:
digit_11 = 'X'
isbn += str(digit_11)
lbl.config(text=isbn)
top = Tk()
top.geometry("450x450+500+300")
top.title("Test")
button = Button(top, text="OK", command=lambda: find_isbn(mEntry.get(), mlabel2), fg="red", bg="blue")
button.pack()
label = Label(top, text="Please enter the 10 digit number")
label.pack()
mEntry = Entry(top)
mEntry.pack()
mlabel2 = Label(top, text='')
mlabel2.pack()
top.mainloop()
You also need to call .mainloop(), on your master widget to get the whole things started. It's also better to call .pack() on an object on a separate line. pack() and grid() return nothing so you won't be able to use other methods on the object once you do that.

Categories