I have created multiple windows and i want to print and store data entered in one of the TopLevel windows but it not able to store and print the data. The same thing when Iam doing without multiple windows,Iam able to do that. What can be wrong here, let me know.
from tkinter import *
def Read():
name = namevalue.get()
print('Name:',name)
with open('attendance_data/detail.csv','a+') as f:
f.write(name)
def New():
top1 = Toplevel()
top1.geometry('500x500')
top1.resizable(False,False)
top1.title('Existing Employee Details')
l1 = Label(top1,text='New Employee Registeration',font='comicsans 14 bold',padx=10).grid(row = 0,column=3,pady=50)
name = Label(top1,text='Name',padx=20)
name.grid(row=1,column=2)
namevalue = StringVar()
nameEntry = Entry(top1,textvariable=namevalue).grid(row=1,column=3,pady=25)
Button(top1,text='Submit',command=Read).grid(row=4,column=3,pady=25) # command
top1.mainloop()
root = Tk()
root.geometry('500x500')
root.resizable(False,False)
root.title('Main Window')
l2 = Label(root,text='New Employee Registeration',font='comicsans 14 bold',padx=10).grid(row = 0,column=2,pady=50,padx=50)
b1 = Button(text='New Employee',bg='black',fg='red',font='comicsansms 12 bold',command=New).grid(row=10,column=2,pady=50)
b2 = Button(text='Existing Employee',bg='black',fg='red',font= 'comicsansms 12 bold').grid(row = 11,column=2,pady=50)
root.mainloop()
I am able to print and store the entered data when iam not using Mutiple Windows
from tkinter import *
def Read():
name = namevalue.get()
print('Name:',name)
with open('attendance_data/detail.csv','a+') as f:
f.write(name)
root = Tk()
root.geometry('500x500')
root.resizable(False,False)
root.title('Main Window')
name = Label(root,text='Name',padx=20)
name.grid(row=1,column=2)
namevalue = StringVar()
nameEntry = Entry(root,textvariable=namevalue).grid(row=1,column=3,pady=25)
Button(root,text='Submit',command=Read).grid(row=4,column=3,pady=25) # command
root.mainloop()
Help me in this.
You forgot to add a command to the second button:
b2 = Button(..., command=Read).grid(row = 11,column=2,pady=50)
Thing to note is, you don't have to store the value in variable as the value of b2 is None, so you might as well remove the variable.
Edit:
You need to make the entry, namevalue, a global variable so it can be accessed outside New and inside Read and other functions.
def New():
global namevalue
....
Hi i am trying to print the sum of the numbers that will be written in the entry boxes but I think there is a problem with changing list into int form. I keep getting this error
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Entry'
from tkinter import *
window = Tk()
window.title=("card")
window.geometry('1500x100')
entries = []
def total():
for entry in entries:
global sum
sum = sum + int(entry)
e1.insert(0,sum)
for i in range(10):
en = Entry(window)
en.grid(row=1, column=0+i)
entries.append(en)
b1=Button(window,text="dsf",command=total).grid(row=7,column=1)
e1=Entry(window).grid(row=20,column=2)
window.mainloop()
Your code have multiple issues,see code below.
import tkinter as tk #dont use wildcard imports to avoid name conflicts
window = tk.Tk()
window.title=("card")
window.geometry('1500x100')
entries = []
def total():
summa = 0 #dont use reserved names like sum or all
for entry in entries:
summa += int(entry.get())#+entrys content as int
e1.delete(0, 'end')#clear entry
e1.insert(0,summa)
for i in range(3):
en = tk.Entry(window)
en.grid(row=1, column=0+i)
entries.append(en)
b1=tk.Button(window,text="dsf",command=total)#split construction
b1.grid(row=7,column=1)#######################from geometry method
e1=tk.Entry(window)
e1.grid(row=20,column=2)
window.mainloop()
I'm working on a project and i would like to get the Value of an Entry created in a def (turned on by a button on Tkinter)
So I have my main tkinter menu, with a button which will call the def "panier".
The def "panier" is creating the Entry "value" and another button to call a second def "calcul".
The second def "calcul" will do things with the value of Entry...
But then, in the def "calcul", when i'm trying to do value.get() it tells "NameError: name 'value' is not defined"
Here is the code, btw the Entry must be created by the def...
from tkinter import *
def panier():
value=Entry(test)
value.pack()
t2=Button(test,text="Validate",command=calcul)
t2.pack()
def calcul(value):
a=value.get()
#here will be the different calculations I'll do
test=Tk()
t1=Button(test,text="Button",command=panier)
t1.pack()
test.mainloop()
Appreciate every feedback :)
You can make the variable global like this:
from tkinter import *
def panier():
global value
value = Entry(test)
value.pack()
t2 = Button(test, text="Validate", command=calcul)
t2.pack()
def calcul():
a = value.get()
print(a)
#here will be the different calculations I'll do
test = Tk()
t1 = Button(test, text="Button", command=panier)
t1.pack()
test.mainloop()
The global value line makes the variable global so you can use it anywhere in your program.
You can also pass in the variable as an argument like what #JacksonPro suggested
t2 = Button(test, text="Validate", command=lambda: calcul(value))
This is one way to do it. Globally create a collection (list or dictionary) to hold a reference to the Entry. When you create the Entry, add it to the collection. I made it with either a list or dictionary for holding the references, so toggle the commented variations in all three places to try it both ways.
import tkinter as tk
def panier():
for item in ('value', ):
ent = tk.Entry(test)
collection.append(ent)
# collection[item] = ent
ent.pack()
t2 = tk.Button(test,text="Validate",command=calcul)
t2.pack()
def calcul():
a = collection[0].get()
# a = collection['value'].get()
print(a)
collection = []
# collection = {}
test = tk.Tk()
t1 = tk.Button(test, text="Button", command=panier)
t1.pack()
test.mainloop()
I want to make a python program to look like this
so I have made a code similar looking this:
from Tkinter import *
import Tkinter
import tkMessageBox
top=Tkinter.Tk()
def and1(a,b):
print int(a and b)
def or1(a,b):
print int(a or b)
def not1(a):
print int(not a)
def xor1(a,b):
print int((a and not b) or (not a and b))
def exit1(top):
top.destroy()
def exit2(top):
top.destroy()
def expl():
top=Tkinter.Tk()
l1=Label(top,text="Number 1").grid(row=0,column=0)
e1=Entry(top,bd=5)
e1.grid(row=0,column=1)
e3=Entry(top,bd=5)
l3=Label(top,text="Binary Number 1").grid(row=0,column=2)
e3.grid(row=0,column=3)
l2=Label(top,text="Number 2").grid(row=1,column=0)
e2=Entry(top,bd=5)
e2.grid(row=1,column=1)
l4=Label(top,text="Binary Number 2").grid(row=1,column=2)
e4=Entry(top,bd=5)
e4.grid(row=1,column=3)
l5=Label(top,text="t.f.p.r.s").grid(row=2,column=2) #says text from previous radiobutton selection
e5=Entry(top,bd=5)
e5.grid(row=2,column=3)
l6=Label(top,text="Decimal Result").grid(row=3,column=1)
e6=Entry(top,bd=5)
e6.grid(row=3,column=2)
b1=Tkinter.Button(top,bd=5,text="Exit",command=lambda top=top:exit2(top)).grid(row=4,column=0)
top.mainloop()
L1=Label(top,text="Number 1").grid(row=0,column=0)
E1=Entry(top,bd=5)
E1.grid(row=0,column=1)
L2=Label(top,text="Number 2").grid(row=0,column=2)
E2=Entry(top,bd=5)
E2.grid(row=0,column=3)
var=IntVar()
R1=Radiobutton(top,text="AND",variable=var,value=1,command="and1")
R1.grid(row=1,column=0)
R2=Radiobutton(top,text="OR",variable=var,value=2,command="or1")
R2.grid(row=1,column=1)
R3=Radiobutton(top,text="NOT",variable=var,value=3,command="not1")
R3.grid(row=2,column=0)
R4=Radiobutton(top,text="XOR",variable=var,value=4,command="xor1")
R4.grid(row=2,column=1)
label=Label(top)
label.grid()
B1=Tkinter.Button(top,text="Result is:",command="result",bd=5)
B1.grid(row=3,column=0)
B2=Tkinter.Button(top,text="Explanation",command=expl,bd=5)
B2.grid(row=3,column=1)
B3=Tkinter.Button(top,bd=5,text="Exit",command=lambda top=top:exit1(top)).grid(row=3,column=2)
L3=Label(top,text="Result is:").grid(row=4,column=0)
E3=Entry(top,bd=5)
E3.grid(row=4,column=1)
top.mainloop()
Now modified. I want that user should input values in first frame and get result accordingly, also on explanation click, other frame opens and explains using that previous values only.
I don't know what to say. I prefer not to completely solve the problem for you, but I wanted to get a better understanding of Python's Tkinker. Read up on classes, it will help in the future.
#!/usr/bin/python
from Tkinter import *
import Tkinter
import tkMessageBox
top=Tkinter.Tk()
res = 0
tfprs = ""
def and1(a,b):
global res
res = int(a and b)
def or1(a,b):
global res
res = int(a | b)
def not1(a):
global res
res = int(not a)
def xor1(a,b):
global res
res = int((a and not b) or (not a and b))
def result(event=None):
global top,res,E3
text = StringVar()
E3=Entry(top,textvariable=text,bd=5)
E3.grid(row=4,column=1)
text.set(str(res))
def exit1(top):
top.destroy()
def exit2(top):
top.destroy()
def selected():
global tfprs
tfprs = var.get()
def expl(a,b):
global top,tfprs,res
binary1 = StringVar()
binary2 = StringVar()
top1=Tkinter.Toplevel(top)
value1 = IntVar()
l1=Label(top1,text="Number 1").grid(row=0,column=0)
e1=Entry(top1,textvariable = value1,bd=5)
value1.set(a)
e1.grid(row=0,column=1)
e3=Entry(top1,textvariable = binary1,bd=5)
l3=Label(top1,text="Binary Number 1").grid(row=0,column=2)
binary1.set(format(a,'b'))
e3.grid(row=0,column=3)
value2 = IntVar()
l2=Label(top1,text="Number 2").grid(row=1,column=0)
e2=Entry(top1,textvariable = value2,bd=5)
value2.set(b)
e2.grid(row=1,column=1)
l4=Label(top1,text="Binary Number 2").grid(row=1,column=2)
e4=Entry(top1,textvariable = binary2,bd=5)
binary2.set(format(b,'b'))
e4.grid(row=1,column=3)
l5=Label(top1,text="t.f.p.r.s").grid(row=2,column=2) #says text from previous radiobutton selection
operator = StringVar()
e5=Entry(top1,textvariable = operator,bd=5)
operator.set(tfprs)
operator.set(tfprs)
e5.grid(row=2,column=3)
dres = IntVar()
l6=Label(top1,text="Decimal Result").grid(row=3,column=1)
e6=Entry(top1,textvariable = dres ,bd=5)
dres.set(res)
e6.grid(row=3,column=2)
b1=Tkinter.Button(top1,bd=5,text="Exit",command=lambda top=top1:exit2(top1)).grid(row=4,column=0)
top.mainloop()
def dotwo(a,b):
selected()
expl(a,b)
num1 = IntVar()
L1=Label(top,text="Number 1").grid(row=0,column=0)
E1=Entry(top,textvariable = num1,bd=5)
num1.set(1)
E1.grid(row=0,column=1)
num2 = IntVar()
L2=Label(top,text="Number 2").grid(row=0,column=2)
E2=Entry(top,textvariable =num2,bd=5)
num2.set(1)
E2.grid(row=0,column=3)
var=StringVar()
R1=Radiobutton(top,text="AND",variable=var,value="AND",command=lambda: and1(int(E1.get()),int(E2.get())))
R1.grid(row=1,column=0)
R2=Radiobutton(top,text="OR",variable=var,value="OR",command=lambda: or1(int(E1.get()),int(E2.get())))
R2.grid(row=1,column=1)
R3=Radiobutton(top,text="NOT",variable=var,value="NOT",command=lambda: not1(int(E1.get())))
R3.grid(row=2,column=0)
R4=Radiobutton(top,text="XOR",variable=var,value="XOR",command=lambda: xor1(int(E1.get()),int(E2.get())))
R4.grid(row=2,column=1)
label=Label(top)
label.grid()
B1=Tkinter.Button(top,text="Result is:",command=result,bd=5)
B1.grid(row=3,column=0)
B2=Tkinter.Button(top,text="Explanation",command=lambda:dotwo(int(E1.get()),int(E2.get())),bd=5)
B2.grid(row=3,column=1)
B3=Tkinter.Button(top,bd=5,text="Exit",command=lambda top=top:exit1(top)).grid(row=3,column=2)
L3=Label(top,text="Result is:").grid(row=4,column=0)
E3=Entry(top,bd=5)
E3.grid(row=4,column=1)
top.mainloop()
This is the code that I have so far. Towards the end I'm having troubles figuring out how to make a popup window saying "Grade is [A]", once the student ID is entered. I also don't know how to create a popup window saying "Student ID not found" if an incorrect ID is entered. I put asterisks by the part I'm having problems with. Thank you!
from Tkinter import *
import tkFont
import tkMessageBox
students = {}
class studentDB :
def __init__(self) : # Constructor
# Sets attributes "studentID", "lastName", "firstName"; sets attribute "scores" as empty list
global students
students[1000] = student(1000, 'abc', (92, 95, 97))
students[1001] = student(1001, 'def', (84, 91, 77))
class student :
def __init__(self, sid, passwd, scoreList) : # Constructor
# Sets attributes "studentID", "lastName", "firstName"; sets attribute "scores" as empty list
self.studentID = sid
self.passwd = passwd
self.scores = scoreList
def getPassword(self) : # Returns the student ID
# Returns attribute "studentID"
return(self.passwd)
def computeAverage(self) : # Computes & returns the total score
# Computes & returns totalScore of list attribute "scores"
totalScore = 0
for val in self.scores :
totalScore = totalScore + val
return(totalScore/float(len(self.scores)))
def getGrade(score) :
if (score >= 90) :
return 'A'
elif (score >= 80) :
return 'B'
elif (score >= 70) :
return 'C'
elif (score >= 60) :
return 'D'
else :
return 'F'
class myApp :
def __init__(self, top) :
# Creates a window with:
# Label and text box for "Student's ID";
# Button labeled "Get Grade" to get the grade for the student; and
# Button labeled "Quit" to quit the application
# You must write the rest of the myApp constructor, here.
self.root = top
self.bframe = Frame(self.root) # Create a container Frame at the bottom
self.bframe.pack(side=BOTTOM)
self.xlabel = Label(self.root, text="Student ID") # Create Label
self.xlabel.pack(side=LEFT)
self.xentry = Entry(self.root, bd=5) # Create Entry box
self.xentry.pack(side=LEFT)
self.xentry.focus_set() # Set focus in Entry box
self.xopen = Button(self.root, text="Get Grade", command=self.showGrade) # Create open Button
self.xopen.pack(side=LEFT)
self.xquit = Button(self.bframe, text="Quit", command=self.quitit) # Create quit Button
self.xquit.pack(side=BOTTOM)
def showGrade(self) :
# Creates either:
# Warning message if SID is not found or
# Information messaged with grade
global students
# You must write the rest of the showGrade method, here.
**sid = self.xentry.get()
if
import tkMessageBox**
def quitit(self) :
# Handler for Quit button click
self.root.destroy()
return
# End of myApp class
studentDB()
top = Tk()
app = myApp(top)
top.mainloop()
Below is python 3 which I use. It should give you the idea. I believe the code is very similar in python 2 with a few minor changes.
# import the messagebox dialogs
from tkinter import messagebox
# these will be in the showGrade method
# to show the sid and grade in a message box
messagebox.showinfo('Student Results', 'SID:{0} Grade:{1}'.format(sid, grade))
# to show that sid not found
messagebox.showerror('Error', 'SID:{0} not found'.format(sid))
The messagebox methods show a popup window and the user clicks 'OK' button
You could try creating a new GUI when the button is pressed, see:
def showGrade(self) :
# Creates either:
# Warning message if SID is not found or
# Information messaged with grade
global students
sid = self.xentry.get() #gets entered studentID
##CREATE GUI##
gradewindow = Toplevel()
gradelbl = Label(gradewindow)
gradelbl.pack()
##END CREATION##
try:
grade = #get grade associated with entered studentID
except ValueError:
gradelbl.config(text="Student doesn't exist!")
else:
gradelbl.config(text=grade)
gradewindow.update()
Note how you yourself will have to retreive the associated grade, I'm not experienced with dictionary structures, so I'll leave it up to you.
Heres how it works:
The sid value is retrieved, which the user has entered.
The new GUI is defined and created
Instantly after this, the program checks the fetched grade, if it does not exist within the dictionary, it will return a ValueError, which will be excepted and an error will be displayed within the new window.
If it is found however, then the GUI will display this instead.
Hope this helped.