Class Population Counter. How to put the program all into one - python

I am trying to develop a class population counter. The problem is that when I run it 2 program come up. I wanted my program to be all in one. The counter keeps coming in a separate program and i can't transfer it into my actual program. How do I do this?
Here is my attached files, I am using Python
import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
population = 0
def counter_label(label):
population = 0
def count():
global population
population +=1
label.config(text=str(population))
root = tk.Tk()
label = tk.Label(root)
label.pack()
counter_label(label)
button = tk.Button(root, text='Population Count', command=count).pack()
root.mainloop()
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation:
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()

I think two windows are coming up is because the program runs Tk() twice - one root = tk.Tk() and another in window = Tk(). If you pass your root Tkinter instance to the class ClassPopulation, then it should show one single window.
[EDIT]
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation:
def __init__(self, root_window):
window = self.root_window
window.title("Class population")
population = 0
def counter_label(label):
population = 0
def count():
global population
population +=1
label.config(text=str(population))
root = Tk()
label = tk.Label(root)
label.pack()
ClassPopulation( root )
counter_label(label)
root.mainloop()

Related

Partial search in python tkinter doesn't work

I've got a problem with a part of my code. It's about partial searching in treeview. I found here on stack overflow partial search method and tried to use with my code. It does't work - It doesn't give any results. Code here below:
from tkinter import *
from tkinter import ttk
root = Tk()
sv = StringVar()
ids = []
names = []
def add():
names = tree.insert("",END,values=(e0.get(),e1.get(),e2.get(),e3.get()))
for i in range(len(names)):
ids.append(tree.insert("", "end", text=names[i]))
def command(*args):
selections = []
for i in range(len(names)):
if entry.get() != "" and entry.get() == names[i][:len(entry.get())]:
selections.append(ids[i])
tree.selection_set(selections)
sv.trace("w", command)
entry = Entry(root, textvariable=sv,width=13)
entry.grid(row=2,column=1,rowspan=3,sticky=W)
e0 = Entry(root,width=15)
e0.grid(row=0,column=1,rowspan=1,sticky=W)
e1 = Entry(root,width=15)
e1.grid(row=0,column=1,rowspan=2,sticky=W)
e2 = Entry(root,width=15)
e2.grid(row=0,column=1,rowspan=3,sticky=W)
e3 = Entry(root,width=15)
e3.grid(row=0,column=1,rowspan=4,sticky=W)
btn1 = Button(root,text="add",width=5,command=add)
btn1.grid(row =0,column=0,rowspan=5)
lb1 = Label(root,text="serial num:")
lb1.grid(row =0,column=0,rowspan=1)
lb2 = Label(root,text="medicine\nname ")
lb2.grid(row =0,column=0,rowspan=2)
lb3 = Label(root,text="quatity")
lb3.grid(row =0,column=0,rowspan=3)
lb4 = Label(root,text="expiry Date")
lb4.grid(row =0,column=0,rowspan=4)
lb4 = Label(root,text="search box")
lb4.grid(row =1,column=0,rowspan=6)
#treeview
tree = ttk.Treeview(root,height=25)
tree["columns"]=("one","two","three","four")
tree.column("one",width=120)
tree.column("two",width=160)
tree.column("three",width=130)
tree.column("four",width=160)
tree.heading("one", text="Numer seryjny leku")
tree.heading("two", text="Nazwa Leku")
tree.heading("three", text="Ampułki/Tabletki")
tree.heading("four",text="Data ważności")
tree["show"]="headings"
tree.grid(row=0,column=2,rowspan=6,pady=20)
root.geometry("840x580")
root.mainloop()
The variable names is not defined. You should put a similar line to the following one in the beginning of your code:
names = []
On the other hand, you have to declare the command function as follows to make it work, since the trace callback expects at least three arguments:
def command(*args):
By the way, if you do not want to loose the data in variable names, I would transform your code in a class-oriented way, such as the following one:
from tkinter import *
from tkinter import ttk
root = Tk()
sv = StringVar()
ids = []
class Tree():
def __init__(self, root):
self.names = []
sv.trace("w", self.command)
self.entry = Entry(root, textvariable=sv, width=13)
self.entry.grid(row=2,column=1,rowspan=3,sticky=W)
self.e0 = Entry(root,width=15)
self.e0.grid(row=0,column=1,rowspan=1,sticky=W)
self.e1 = Entry(root,width=15)
self.e1.grid(row=0,column=1,rowspan=2,sticky=W)
self.e2 = Entry(root,width=15)
self.e2.grid(row=0,column=1,rowspan=3,sticky=W)
self.e3 = Entry(root,width=15)
self.e3.grid(row=0,column=1,rowspan=4,sticky=W)
self.btn1 = Button(root,text="add",width=5,command=self.add)
self.btn1.grid(row =0,column=0,rowspan=5)
self.lb1 = Label(root,text="serial num:")
self.lb1.grid(row =0,column=0,rowspan=1)
self.lb2 = Label(root,text="medicine\nname ")
self.lb2.grid(row =0,column=0,rowspan=2)
self.lb3 = Label(root,text="quatity")
self.lb3.grid(row =0,column=0,rowspan=3)
self.lb4 = Label(root,text="expiry Date")
self.lb4.grid(row =0,column=0,rowspan=4)
self.lb4 = Label(root,text="search box")
self.lb4.grid(row =1,column=0,rowspan=6)
#treeview
self.tree = ttk.Treeview(root,height=25)
self.tree["columns"]=("one","two","three","four")
self.tree.column("one",width=120)
self.tree.column("two",width=160)
self.tree.column("three",width=130)
self.tree.column("four",width=160)
self.tree.heading("one", text="Numer seryjny leku")
self.tree.heading("two", text="Nazwa Leku")
self.tree.heading("three", text="Ampułki/Tabletki")
self.tree.heading("four",text="Data ważności")
self.tree["show"]="headings"
self.tree.grid(row=0,column=2,rowspan=6,pady=20)
def add(self):
self.names = self.tree.insert("",END,values=(self.e0.get(),self.e1.get(),self.e2.get(),self.e3.get()))
for i in range(len(self.names)):
ids.append(self.tree.insert("", "end", text=self.names[i]))
def command(self, *args):
selections = []
for i in range(len(self.names)):
if self.entry.get() != "" and self.entry.get() == self.names[i][:len(self.entry.get())]:
selections.append(ids[i])
self.tree.selection_set(selections)
tree = Tree(root)
root.geometry("840x580")
root.mainloop()

creating button with tkinter

I was really curious why I cannot get my add_button to work,
as the window fails to come up when creating it.
from tkinter import *
class Calculator:
#-------------------------------------------------
def __init__(self, master):
self.master = master
master.title("Calculator")
self.close_button = Button(master, text = "Close", command = master.destroy)
Label(master, text = "First Digit").grid(row = 0)
Label(master, text = "Second Digit").grid(row = 1)
self.input1 = 0
self.input2 = 0
input1 = Entry(master)
input2 = Entry(master)
input1.grid(row = 0, column = 1)
input2.grid(row = 1, column = 1)
self.close_button.grid(row = 2, column = 0)
self.add_buton = Button(master, text = "Add", command = self.add())
self.add_button.grid(row = 2, column = 1)
master.configure(background = 'grey')
return
#-------------------------------------------------
def add(self):
return self.input1.get() + self.input2.get()
#-------------------------------------------------
#-------------------------------------------------
root = Tk()
calc = Calculator(root)
root.mainloop()
#-------------------------------------------------
Welcome to Stack!
I've looked through you code I've been able to do what you are asking. There were a few errors within your code:
a) you had self.add_buton and self.add_button which caused an error.
b) self.input1 = 0 and self.input2 = 0 are not required.
c) You were calling self.add() as the command and you should be calling self.add. When calling it as a command you do not need ()
d)input1 = Entry(master) should be self.input1 = tk.Entry(master)
e) You should convert your input values into int or float as otherwise it will just one value onto the end of the other. (Eg, 1 + 5 = 15 whereas int(1) + int(5) = 6
Here is your code with the entry boxes working as they should. I have import tkinter as tk hence why it is tk.Entry
from tkinter import *
import tkinter as tk
class Calculator:
#-------------------------------------------------
def __init__(self, master):
self.master = master
master.title("Calculator")
self.close_button = Button(master, text = "Close", command = master.destroy)
Label(master, text = "First Digit").grid(row = 0)
Label(master, text = "Second Digit").grid(row = 1)
self.input1 = tk.Entry(bd=5, width=35, background='gray35', foreground='snow')
self.input2 = tk.Entry(bd=5, width=35, background='gray35', foreground='snow')
self.input1.grid(row = 0, column = 1)
self.input2.grid(row = 1, column = 1)
self.close_button.grid(row = 2, column = 0)
self.add_button = tk.Button(master, text = "Add", command = self.add)
self.add_button.grid(row = 2, column = 1)
master.configure(background = 'grey')
return
#-------------------------------------------------
def add(self):
val = self.input1.get()
print(val)
#-------------------------------------------------
#-------------------------------------------------
root = Tk()
calc = Calculator(root)
root.mainloop()
This should now work how you wanted it too. The variables within the entry can be changed to suit. You were correct in calling the value of the entry with self.input1.get().
Hope this has helped.

Counting the number of times button is clicked during my program

I am doing a program on a class list counter. I have one program, in frame 5 underneath "Population Count" and where it says 0, it is meant to increase by one for every time the button "Add to classlist" is clicked every time. I tried many different methods but all of those I tried never seem to work. It would be appreciative if anyone can help.
Here is my coding so far, the rest I have done for my class list counter
import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation():
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
population = 0
def population(label):
population = 0
def mbutton():
global population
population +=1
label.config(text=str(population))
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()
Rather than using a global population you need to declare self.population = 0 in your __init__ method and to increment self.population in your button click handler. It is normally also considered good practice to have a class method to get the value.
Possible solution: if all you want to do is, have the population count, and increment it on each button click:
import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation():
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
# population = 0
self.population = 0 # made it a class attr
# def population(label):
# population = 0
def add_population(self):
# having it separate can help in modification or enhancement
self.population +=1
def mbutton():
# global population
# population +=1
self.add_population() # increment
label.config(text=str(population))
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()
Edit 1: I have added the complete code, with my suggested changes - previous statements are commented, so you know the changes.

python error run from cmd

For my coursework i am doing a booking system which uses some tree views. The problem is that if ran from cmd when i double click on a row in the tree view it does not populate the boxes below it, however if i run it from the idle it does. Below is my where i have made my class and two defs which are create_GUI(for first part of gui before double click) and double click(makes second part of GUI)
from tkinter import *
import os
import datetime
import sqlite3
from tkinter.ttk import Combobox,Treeview,Scrollbar
import tkinter as tk
import Utilities
class Application(Frame):
""" Binary to Decimal """
def __init__(self, master):
""" Initialize the frame. """
super(Application, self).__init__(master)
self.grid()
self.create_GUI()
def Quit(self):
self.master.destroy()
def create_GUI(self):
frame1 = tk.LabelFrame(root, text="frame1", width=300, height=130, bd=5)
frame2 = tk.LabelFrame(root, text="frame2", width=300, height=130, bd=5)
frame1.grid(row=0, column=0, columnspan=3, padx=8)
frame2.grid(row=1, column=0, columnspan=3, padx=8)
self.title_lbl = Label(frame1, text = "Students")
self.title_lbl.grid(row = 0, column = 2)
self.fn_lbl = Label(frame1, text = "First Name:")
self.fn_lbl.grid(row = 1 , column = 1)
self.fn_txt = Entry(frame1)
self.fn_txt.grid(row = 1, column = 2)
self.ln_lbl =Label(frame1, text = "Last Name:")
self.ln_lbl.grid(row = 2, column = 1)
self.ln_txt = Entry(frame1)
self.ln_txt.grid(row = 2, column = 2)
self.q_btn = Button(frame1, text = "Back",padx=80,pady=10, command = lambda: self.Quit())
self.q_btn.grid(row = 3, column = 0)
self.s_btn = Button(frame1, text = "search",padx=80,pady=10, command = lambda: self.search())
self.s_btn.grid(row = 3,column = 3)
self.tree = Treeview(frame2,height = 6)
self.tree["columns"] = ("StudentID","First Name","Last Name")#,"House Number", "Street Name", "Town Or City Name","PostCode","MobilePhoneNumber")
self.tree.column("StudentID",width = 100)
self.tree.column("First Name",width = 100)
self.tree.column("Last Name", width = 100)
## self.tree.column("House Number", width = 60)
## self.tree.column("Street Name", width = 60)
## self.tree.column("Town Or City Name", width = 60)
## self.tree.column("PostCode", width = 60)
## self.tree.column("MobilePhoneNumber", width = 60)
self.tree.heading("StudentID",text="StudentID")
self.tree.heading("First Name",text="First Name")
self.tree.heading("Last Name",text="Last Name")
## self.tree.heading("House Number",text="House Number")
## self.tree.heading("Street Name",text="Street Name")
## self.tree.heading("Town Or City Name",text="Town Or City Name")
## self.tree.heading("PostCode",text="PostCode")
## self.tree.heading("MobilePhoneNumber",text="MobilePhoneNumber")
self.tree["show"] = "headings"
yscrollbar = Scrollbar(frame2, orient='vertical', command=self.tree.yview)
xscrollbar = Scrollbar(frame2, orient='horizontal', command=self.tree.xview)
self.tree.configure(yscroll=yscrollbar.set, xscroll=xscrollbar.set)
yscrollbar.grid(row=1, column=5, padx=2, pady=2, sticky=NS)
self.tree.grid(row=1,column=0,columnspan =5, padx=2,pady=2,sticky =NSEW)
self.tree.bind("<Double-1>",lambda event :self.OnDoubleClick(event))
def OnDoubleClick(self, event):
frame3 = tk.LabelFrame(root, text="frame1", width=300, height=130, bd=5)
frame3.grid(row=2, column=0, columnspan=3, padx=8)
self.message=StringVar()
self.message.set("")
self.lblupdate = Label(frame3, textvariable = self.message).grid(row=0,column=0,sticky=W)
curItem = self.tree.focus()
contents =(self.tree.item(curItem))
StudentDetails = contents['values']
print(StudentDetails)
self.tStudentID=StringVar()
self.tFirstName = StringVar()
self.tLastName = StringVar()
self.tHouseNumber = StringVar()
self.tStreetName = StringVar()
self.tTownOrCityName = StringVar()
self.tPostCode = StringVar()
self.tEmail = StringVar()
self.tMobilePhoneNumber = StringVar()
self.tStudentID.set(StudentDetails[0])
self.tFirstName.set(StudentDetails[1])
self.tLastName.set(StudentDetails[2])
self.tHouseNumber.set(StudentDetails[3])
self.tStreetName.set(StudentDetails[4])
self.tTownOrCityName.set(StudentDetails[5])
self.tPostCode.set(StudentDetails[6])
self.tEmail.set(StudentDetails[7])
self.tMobilePhoneNumber.set(StudentDetails[8])
self.inst_lbl0 = Label(frame3, text = "Student ID").grid(row=5,column=0,sticky=W)
self.StudentID = Label(frame3, textvariable=self.tStudentID).grid(row =5,column=1,stick=W)
self.inst_lbl1 = Label(frame3, text = "First Name").grid(row=6,column=0,sticky=W)
self.NFirstName = Entry(frame3, textvariable=self.tFirstName).grid(row =6,column=1,stick=W)
self.inst_lbl2 = Label(frame3, text = "Last Name").grid(row=7,column=0,sticky=W)
self.NLastName = Entry(frame3, textvariable=self.tLastName).grid(row =7,column=1,stick=W)
self.inst_lbl3 = Label(frame3, text = "House Number").grid(row=8,column=0,sticky=W)
self.HouseNumber = Entry(frame3,textvariable=self.tHouseNumber).grid(row=8,column=1,sticky=W)
self.inst_lbl4 = Label(frame3, text = "Street Name").grid(row=9,column=0,sticky=W)
self.StreetName =Entry(frame3,textvariable=self.tStreetName).grid(row=9,column=1,sticky=W)
self.inst_lbl5 = Label(frame3, text = "Town or City Name").grid(row=10,column=0,sticky=W)
self.TownOrCityName =Entry(frame3,textvariable=self.tTownOrCityName).grid(row=10,column=1,sticky=W)
self.inst_lbl6 = Label(frame3, text = "Postcode").grid(row=11,column=0,sticky=W)
self.PostCode = Entry(frame3,textvariable=self.tPostCode).grid(row=11,column=1,sticky=W)
self.inst_lbl7 = Label(frame3, text = "Email").grid(row=12,column=0,sticky=W)
self.Email =Entry(frame3,textvariable=self.tEmail).grid(row=12,column=1,sticky=W)
self.inst_lbl8 = Label(frame3, text = "Mobile phonenumber").grid(row=13,column=0,sticky=W)
self.MobilePhoneNumber =Entry(frame3,textvariable=self.tMobilePhoneNumber).grid(row=13,column=1,sticky=W)
self.btnSaveChanges = Button(frame3, text = "save changes",padx=80,pady=10,command = lambda:self.SaveChanges()).grid(row=14,column=0,sticky=W)
self.btnSaveChanges = Button(frame3, text = "delete record",padx=80,pady=10,command = lambda:self.DeleteRecord()).grid(row=14,column=1,sticky=W)
def search(self):
FirstName = self.fn_txt.get()
LastName = self.ln_txt.get()
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
cursor.row_factory = sqlite3.Row
sql = "select StudentID,FirstName,LastName,HouseNumber,StreetName,TownOrCityName,PostCode,Email,MobilePhoneNumber"\
" from tblStudents"\
" where FirstName like ?"\
" and LastName like ?"
cursor.execute(sql,("%"+FirstName+"%","%"+LastName+"%",))
StudentList = cursor.fetchall()
print(StudentList)
self.loadStudents(StudentList)
def loadStudents(self,StudentList):
for i in self.tree.get_children():
self.tree.delete(i)
for student in StudentList:
self.tree.insert("" , 0,values=(student[0],student[1],student[2],student[3],student[4],student[5],student[6],student[7],student[8]))
def SaveChanges(self):
valid = True
self.message.set("")
NFirstName = self.tFirstName.get()
NLastName = self.tLastName.get()
NHouseNumber = self.tHouseNumber.get()
NStreetName = self.tStreetName.get()
NTownOrCityName = self.tTownOrCityName.get()
NPostCode = self.tPostCode.get()
NEmail = self.tEmail.get()
NMobilePhoneNumber = self.tMobilePhoneNumber.get()
StudentID = self.tStudentID.get()
if NFirstName == "" or NLastName == "" or NEmail == "" or NMobilePhoneNumber == "":
valid = False
self.message.set('missing details,first name,last name,phone number, email are all needed')
if not Utilities.is_phone_number(NMobilePhoneNumber ):
valid = False
self.message.set('invalid mobile phone number')
if not Utilities.is_postcode(NPostCode):
valid = False
self.message.set('invalid postcode')
if not Utilities.is_email(NEmail):
valid = False
self.message.set('invalid email')
if NHouseNumber != "":
if int(NHouseNumber) < 0:
self.message.set('invalid house number')
if valid == True:
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
sql = "update tblStudents set FirstName =?,LastName=?,HouseNumber=?,StreetName=?,TownOrCityName=?,PostCode=?,Email=?,MobilePhoneNumber=? where StudentID=?"
cursor.execute(sql,(NFirstName,NLastName,NHouseNumber,NStreetName,NTownOrCityName,NPostCode,NEmail,NMobilePhoneNumber,StudentID))
db.commit()
self.message.set("student details updated")
def DeleteRecord(self):
StudentID = self.tStudentID.get()
#StudentID = int(StudentID)
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
sql = "delete from tblStudents where StudentID = ?"
cursor.execute(sql,(StudentID))
db.commit()
self.tlabeupdate.set("student details deleted")
root = Tk()
root.title("booking system")
root.geometry("800x800")
root.configure(bg="white")
app = Application(root)
root.mainloop()
EDIT
when i was copyign and pasting the rest of my code that i forgot to put in the original post i found that it only stops working if i open it through the student menu(separate peice of code) but it works if i dont go through the menu
You must call mainloop() on the root window so that your program can process events.
You create LabelFrames in the parent called root, but root does not exist. To correct it pass master to the function, which receives it as root
class Application():
""" Binary to Decimal """
def __init__(self, master):
""" Initialize the frame. """
self.create_GUI(master)
def create_GUI(self, root):
frame1 = tk.LabelFrame(root, text="frame1", width=300, height=130, bd=5)

Refering to Labels Python, Tkinter

I'd like to refer to labels in def check(self) . It should check if feedback from external device equals to something, but I don't know how to refer to label and change colour of it if it's equal or not. I'd like to change for example lab3 background to green or red, depending on equality. Here is my code:
# -*- coding: utf-8 -*-
import Tkinter as T, tkFileDialog
import os
from time import *
import serial
from ttk import Button, Label, Frame, Entry, Style
class Program(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.root = root
self.initUI()
def initUI(self):
self.root.title('OptoMaQ')
Style().configure('TFrame', background = '#6666ff')
Style().configure('TButton',background = '#6666ff')
lab1 = Label(self, text = 'Press Save to save a file', background = '#6666ff').grid(row = 0, columnspan = 5)
but1 = Button(self, text='Save', command=self.save).grid(row = 2,column = 1)
lab2 = Label(self, text = 'Press Exit to quite', background = '#6666ff').grid(row = 1, columnspan = 5)
but2 = Button(self, text = 'Exit',command = self.exit).grid(row = 2, column = 2)
lab3 = Label(self, text = 'Spectra-Hub', background = '#6666ff').grid(row = 3, columnspan = 5)
lab4 = Label(self, text = 'SpectraPro VM-504',background = '#6666ff').grid(row = 4,columnspan = 5)
lab5 = Label(self, text = 'SpectraPro SP-2-300i',background = '#6666ff').grid(row = 5, columnspan = 5)
but3 = Button(self, text = 'Check',command = self.check).grid(row = 6, columnspan = 5)
lab6 = Label(self, text = 'Type sth here', background = '#6666ff').grid(row = 7,columnspan = 5)
self.entry = Entry(self, justify = 'center',text = '1')
self.entry.grid(row = 8, columnspan =3)
self.fileop = options = {}
options['filetypes'] = [('all files', '.*'),('dat files','.dat'),('text files', '.txt')]
options['initialfile'] = 'file.txt'
options['parent'] = root
def check(self):
port = serial.Serial(15)
command = 'WHO'
port.write(command + '\r')
out = port.read(50)
if out == 'Acton Research Corp. \nSpectra-Hub':
lab3 = Label(self, text = 'Spectra-Hub', background = '#6666ff').grid(row = 3, columnspan = 5)
lab3.config(background = 'green')
port.close()
else:
lab3 = Label(self, text = 'Spectra-Hub', background = '#6666ff').grid(row = 3, columnspan = 5)
lab3.config(background = 'red')
port.close()
port2 = serial.Serial(16)
port2.write(command +'\r')
out2 = port2.read(50)
if out2 == 'Acton Research Corp. \nSpectraPro VM-504':
port2.close()
else:
port2.close()
port3 = serial.Serial(17)
port3.write(command + '\r')
out3 = port3.read(46)
if out3 == 'Acton Research Corp. \n SpectraPro SP-2-300i':
port3.close()
else:
port3.close()
def save(self):
filename = tkFileDialog.asksaveasfilename(**self.fileop)
if filename:
file = open(filename, 'a+')
time = strftime("%A, %d %b %Y, %H:%M:%S ", gmtime())
print time
file.write(time)
file.write('\n')
input = str(self.entry.get())
file.write(input)
file.close()
def exit(self):
root.destroy()
if __name__=='__main__':
root = T.Tk()
Program(root).pack()
root.mainloop()
I've tried something like this in lines 46-53 but it doesn't work. It shows that 'NoneType' object has no attribute 'config' in line 52. Any ideas? It's really important to me please help :)
That is because your labels are only defined in the scope of def initUI(self): and therefore inaccessible to def check(self)
Try defining your buttons as self.lab1 instead of lab1 and also refer to them in the same way.

Categories