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) + " %"))
Related
I am trying to make a loan amortization table inside tkinter GUI using text box. However, all the loan amortization table is fully displayed in the terminal console as an output.
The tkinter text BOX output display's only the last line: Here is the full code:
import math
import tkinter as tk
from tkinter import *
def calcLoanPayment(p, r, n, t):
if p > 0 and r > 0 and n > 0 and t > 0:
clp = (p *(r/n)*(pow(1 + r/n, n * t)))/(pow(1 + r/n, n * t)-1)
clp = round(clp, 2)
return clp
else:
return -1
def runApp(): #This will bound the function runapp to the calcbtn.
print("running")
p = principalentry.get() #this will get value as a string
try:
p = float(p) #this will make cast it to float variable.
except:
p = -1
principalentry.delete(0, END) #this will clear the entry after calculation
r = interestrateentry.get()
try: #Try will help from crushing the program when wrong value entered
r = float(r)
except:
r = -1
interestrateentry.delete(0, END) #this will clear the entry after calculation
n = compoundintervalentry.get() #this will get value as a string
try:
n = int(n) #this will make cast it to float variable.
except:
n = -1
compoundintervalentry.delete(0, END) #this will clear the entry after calculation
t = durationentry.get()
try: #Try will help from crushing the program when wrong value entered
t = int(t)
except:
t = -1
durationentry.delete(0, END) #this will clear the entry after calculation
clp = calcLoanPayment(p,r,n,t)
print(clp)
paymentinterval = n*t
paymentinterval = int(paymentinterval)
startingBalance=p
endingBalance=p
for i in range(1, paymentinterval+1):
interestcharge =r/n*startingBalance
endingBalance=startingBalance+interestcharge-clp
result ="\t\t"+str(i)+"\t\t" +str(round (startingBalance, 1)
)+"\t\t"+str(round (interestcharge, 1))+"\t\t"+str(round (clp, 1)
)+"\t\t"+str(round (endingBalance, 1))
startingBalance = endingBalance
print(result)
finaloutput = result
output.config(state="normal")
output.delete(0.0, 'end')
output.insert(END, finaloutput)
output.config(state="disabled")
#Frontend maincode Startshere:
#sketch the design of the user interface first.
root = tk.Tk()
root.config(bg="#F8B135")
root.state("zoomed")
#There are 3 steps to build event programming
#Step 1: construct the widgets
#step 2: configure the widget to make it nicer
#srep 3: place or pack the widget in the root window
title = Label(root, text = "Loan Payment Calculator", font = 'bold')
title.config(fg='white', bg="#28348A")
title.pack(fill = BOTH)
principallabel = Label(root, text="Principal: ")
principallabel.config(anchor = W, font = 'bold', bg="#F8B135")
principallabel.place(x=50, y=30)
principalentry = Entry(root)
principalentry.config(bg="#ffffff")
principalentry.place(x=400, y=30)
interestratelabel = Label(root, text="Interest Rate: enter as Decimal (eg.2% as 0.02) ")
interestratelabel.config(anchor = W, font = 'bold', bg="#F8B135")
interestratelabel.place(x=50, y=70)
interestrateentry = Entry(root)
interestrateentry.config(bg="#ffffff")
interestrateentry.place(x=400, y=70)
compoundintervallabel = Label(root, text="Compound Interval: ")
compoundintervallabel.config(anchor = W, font = 'bold', bg="#F8B135")
compoundintervallabel.place(x=50, y=110)
compoundintervalentry = Entry(root)
compoundintervalentry.config(bg="#ffffff")
compoundintervalentry.place(x=400, y=110)
durationlabel = Label(root, text="Duration: ")
durationlabel.config(anchor = W, font = 'bold', bg="#F8B135")
durationlabel.place(x=50, y=150)
durationentry = Entry(root)
durationentry.config(bg="#ffffff")
durationentry.place(x=400, y= 150)
output = Text(root)
output.config(width= 150, height = 100, bg="white", state="disabled", borderwidth=2, relief= "groove", wrap='word')
output.place(x=50, y=230)
calcbtn = Button(root, text= "Calculate", font = 'bold', highlightbackground="#3E4149")
calcbtn.config(fg='#28348A',command=runApp)
calcbtn.place(x=50, y=190)
root. mainloop()
file.close()`
I couldn't figure out How to display the whole output like the terminal did on the tkinter textbox output function. your help is much appreciated.
There are 2 small changes to the code in the function runApp()
output.config(state="normal")
# output.delete(0.0, 'end') # This line deletes the last entry in the text box. Remove this
output.insert(END, finaloutput + '\n') # Add a newline here. Generates the desired 'tabular' output
output.config(state="disabled")
I have a Python file that when run, opens a window for simple addition practice. It asks the user for their input, and if the total is correct will output "Right!" and "Oops!" for incorrect. Below all of this is a counter that keeps track of the correct number out of the total. However, at the moment, those numbers both remain zero when user enters their input. What kind of changes would need to be made under the ClicktheButton1 function in order to get this program properly functioning? Thanks.
The output would end up looking like "2 out 4 correct" in the window, updating after each new problem is solved.
from tkinter import *
import random as rn
window = Tk()
window.geometry('350x350')
window.title("C200")
x = rn.randint(0,100)
y = rn.randint(0,100)
correct, incorrect = 0,0
myLabel = Label(window, text="{0}+{1}=".format(x,y), font=("Arial Bold", 15))
myLabel.grid(column=0, row=0)
myLable2 = Label(window, text = "",font=("Arial Bold", 15))
myLable2.grid(column=0, row=5)
mylabel3 = Label(window,text = "0 out of 0 correct",font=("Arial Bold", 15))
mylabel3.grid(column=0, row=10)
mytxt = Entry(window, width=12)
mytxt.grid(column=1,row=0)
def ClicktheButton1():
global x
global y
global correct
global incorrect
myguess = int(mytxt.get())
if x + y == myguess:
myLable2.configure(text = "Right!")
correct += 1
else:
myLable2.configure(text = "Oops!")
incorrect += 1
x = rn.randint(0,100)
y = rn.randint(0,100)
mytxt.focus()
mytxt.delete(0,END)
myLabel.configure(text = "{0}+{1}=".format(x,y))
btn1 = Button(window, text="check", command = ClicktheButton1)
btn1.grid(column=0, row=7)
def ClicktheButton2():
window.destroy()
btn1 = Button(window, text="Quit", command = ClicktheButton2)
btn1.grid(column=400, row=400)
window.mainloop()
You have to change text in mylabel3 in the same why as you change text in myLabel - and even in the same place. I don't know why you have problem with this.
myLabel.configure(text = "{0}+{1}=".format(x,y))
mylabel3.configure(text="{0} of {1} correct".format(correct, correct+incorrect))
I've a Tkinter-programm where I regularly (10 times/second) update Labels with certain sensor-values.
The problem is that they are arranged with .grid right next to each other and when a value gets/loses a place (e.g. 10 -> 9, 60 -> 150, you see the number needs extra space) the label jumps back and forth (because the number gains or loses a space and therefore .grid responds by adjusting the Label).
How can i avoid that? Do I need to change Text & Numbers to a certain font or is there a function that fixes the Labels place? I'd be happy about useful answers.
Here's a code example (please notice how the labels are adjusting cause that's the problem):
#!/usr/bin/env
import sys
import time
import subprocess
from Tkinter import *
import numpy
import random
i = 0
x = 0
def GetValue():
x = random.randint(0,10000)
time.sleep(0.1)
return x
def UebergabeTkinter():
while 1:
CompleteValue = GetValue()
Variable1.set(CompleteValue)
Variable2.set(CompleteValue)
Variable3.set(CompleteValue)
Variable4.set(CompleteValue)
root.update()
def Exit():
root.destroy()
return
try:
root = Tk()
Leiste = Menu(root)
root.config(menu = Leiste)
DateiMenu = Menu(Leiste)
Leiste.add_cascade(label = "datei", menu = DateiMenu)
DateiMenu.add_command(label = "Exit", command = Exit)
EditMenu = Menu(Leiste)
Leiste.add_cascade(label = "edit", menu = EditMenu)
Variable1 = IntVar()
Variable2 = IntVar()
Variable3 = IntVar()
Variable4 = IntVar()
Ausgang = 0
for column in range(0,8,2):
String1 = "Ausgang "
String1 += `Ausgang`
Ausgang = Ausgang + 1
Label(text = String1).grid(row=0,column=column)
Ausgang = 0
for column in range(0,8,2):
String1 = "Der Wert von "
String2 = " ist: "
String1 += `Ausgang`
Ausgang = Ausgang + 1
String3 = String1+String2
Label(text = String3).grid(row=2,column=column)
Label1 = Label(root, textvariable = Variable1)
Label1.grid(row = 2, column = 1, sticky = W+E+N+S)
Label2 = Label(root, textvariable = Variable2)
Label2.grid(row = 2, column = 3, sticky = W+E+N+S)
Label3 = Label(root, textvariable = Variable3)
Label3.grid(row = 2, column = 5, sticky = W+E+N+S)
Label4 = Label(root, textvariable = Variable4)
Label4.grid(row = 2, column = 7, sticky = W+E+N+S)
UebergabeTkinter()
root.mainloop()
except KeyboardInterrupt:
print "Hallo"
You can give labels a fixed width:
Label1 = Label(root, textvariable=Variable1, width=4)
Just make sure they are large enough to fit every number that could be put in, since of course next no the label not shrinking when the number is shorter, this also means that they will not grow to fit larger numbers.
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()
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.