Python - tkinter - tree - database questions - python

I have a database with a customers table with the fields(id, name,surname, DOB).
I have created a treeview which displays name and surname but soon as i try to insert the DOB in to the treeview i get an error Column index 3 out of bounds.
Also please can you explain how treeview actually works as i have copied the code from a tutorial and adapted it but still dont fully understand it.
from tkinter import *
from tkinter import ttk
import sqlite3
import os.path
class Product:
db_name = 'database.db'
def __init__(self, wind):
self.wind = wind
self.wind.title('IT Products')
frame = LabelFrame (self.wind, text = 'Add new record')
frame.grid (row = 0, column = 1)
Label (frame, text = 'Name: ').grid (row = 1, column = 1)
self.name = Entry (frame)
self.name.grid(row = 1, column = 2)
Label (frame, text = 'Surname: ').grid (row = 2, column = 1)
self.price = Entry (frame)
self.price.grid(row = 2, column = 2)
ttk.Button (frame, text= 'Add record', command = self.adding).grid (row = 3, column =2 )
self.message = Label (text = '',fg = 'red')
self.message.grid (row = 3, column = 0)
self.tree = ttk.Treeview (height = 10, colum = 2)
self.tree.grid(row = 100, column = 0, columnspan = 100)
self.tree.heading('#0', text = 'Name', anchor = W)
self.tree.heading(2, text = 'Surname', anchor = W)
self.tree.heading(3, text = 'DOB', anchor = W)
self.tree.heading(3, text = "column B")
ttk.Button (text = 'Delete record', command = self.deleting).grid (row = 10, column = 5)
ttk.Button (text = 'Edit record').grid (row = 10, column = 1)
self.viewing_records()
def run_query (self, query, parameters = ()):
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
query_result = cursor.execute (query, parameters)
conn.commit()
return query_result
def viewing_records(self):
records = self.tree.get_children()
for element in records:
self.tree.delete (element)
query = 'SELECT * FROM customers '
db_rows = self.run_query (query)
for row in db_rows:
## self.tree.insert('', 2, text=str(), values=(row[1], row[2],
row[3]))
self.tree.insert ('', 2, text = row[1], values=(row[1], row[2], row[3]))
def validation(self):
return len (self.name.get()) != 0 and len (self.price.get()) != 0
def adding (self):
if self.validation ():
query = 'INSERT INTO customersVALUES (NULL, ?, ?)'
parameters = (self.name.get(), self.price.get())
self.run_query (query, parameters)
self.message['text'] = 'Record {} added'.format (self.name.get())
self.name.delete (0, END)
self.price.delete (0,END)
else:
self.message['text'] = 'Name field or price is empty'
self.viewing_records()
def deleting (self):
self.message ['text'] = ''
try:
self.tree.item(self.tree.selection()) [ 'values'] [0]
except IndexError as e:
self.message[text] = 'Please select record'
return
self. message['text'] = ''
name = self.tree.item(self.tree.selection())['text']
query = 'DELETE FROM customers WHERE name = ?'
self.run_query(query, (name,))
self.message['text'] = 'Record {} deleted'.format(name)
self.viewing_records()
if __name__ == '__main__':
wind = Tk()
application = Product (wind)
wind.mainloop()

To avoid column index error, provide a list of column identifiers as show below:
self.tree = ttk.Treeview(height=10, columns=("lname", "sex", "sdate", "dob"))
self.tree.grid(row=100, column=0, columnspan=100)
self.tree.heading('#0', text='First Name', anchor=W)
self.tree.heading("lname", text='Last Name', anchor=W)
self.tree.heading("sex", text='Gender', anchor=W)
self.tree.heading("sdate", text='Start Date', anchor=W)
self.tree.heading("dob", text='Birth Date', anchor=W)

Related

Tkinter: How to make one button with multiple text fields?

I have this table in tkinter. However, I want to have only one button in each row with four text fields. (I currently have four buttons in each row.)
Basically, I want to connect these four buttons to one button in a row. How can I do this?
from tkinter import *
class Table:
def __init__(self,root):
# code for creating table
for i in range(total_rows):
for j in range(total_columns):
self.e = Button(root, width=20,text = lst[i][j])
self.e.grid(row=i, column=j)
# take the data
lst = [(1,'Raj','Mumbai',19),
(2,'Aaryan','Pune',18),
(3,'Vaishnavi','Mumbai',20),
(4,'Rachna','Mumbai',21),
(5,'Shubham','Delhi',21)]
# find total number of rows and
# columns in list
total_rows = len(lst)
total_columns = len(lst[0])
# create root window
root = Tk()
t = Table(root)
root.mainloop()
I've modified your code to include a Toplevel window called 'work' that gives access to the super buttons. The quantity of buttons is determined by the number of rows in table.
Each button is connected to another Toplevel window called 'edit'.
'Edit' contains Label, Entry and Button objects. The quantity is determined by the number of columns in table.
All windows are resizable with 'work' and 'edit' windows accessible via F1 key.
Escape key will close 'top' table via messagebox.
Ok this is the latest version.
I've divided the project into two python files, a data file called 'Datafile.py' and code called "Records.py'.
'Datafile.py' must be saved separately from 'Records.py.
Records code is completely configurable by changing table data in Datafile.py
Changing table data by adding or modifying columns and/or rows will configure the main program. The table, work and edit windows are determined by the row and columns in Datafile.py
SAVE THIS AS 'Datafile.py'
import time
timedate = time.localtime()
year = timedate.tm_year
indice = [ "gender", "name", "location", "age", "birth"]
table = [
["Male", "Raj", "Mumbai", 19, year-19],
["Male", "Aaryan", "Pune", 18, year-18],
["Female", "Vaishnavi","Mumbai", 20, year-20],
["Female", "Rachna", "Mumbai", 21, year-21],
["Male", "Shubham", "Delhi", 21, year-21],
["Male", "Roger", "New York", 17, year-17],
["Male", "David", "Sydney", 53, year-53],
["Female", "Jennifer", "London", 42, year-42]]
Here is the main program 'Records.py'.
SAVE AS 'Records.py'
import tkinter as tk
from tkinter import messagebox
from Datafile import timedate, indice, table
class Table:
def __init__(self, master):
self.master = root
self.master.title("Table")
# create table of buttons in self.store
self.rows = len(table)
self.columns = len(table[0])
# number of rows and columns
self.store = []
for r in range(self.rows):
self.store.append([])
for c in range(self.columns):
e = tk.Label(
self.master, width = 20, bd = 1,
relief = "raised", text = table[r][c])
e.grid(row = r, column = c, sticky = tk.NSEW)
self.flexx(self.master, r = r, c = c)
self.store[r].append(e) # all table buttons stored in list
self.master.geometry(f"{self.columns*100}x{self.rows*26}")
self.master.update()
# create toplevel widget for buttons
self.work = tk.Toplevel(self.master)
self.work.transient(self.master)
self.work.withdraw()
self.work.title("Individual Selector")
# populate toplevel widget with the Super buttons
# make buttons resizable
for r in range(self.rows):
e = tk.Button(
self.work, text = f"{table[r][1]}", bd = 1,
command = self.redirect(self.access, r))
e.grid(row=r, column=0, sticky = tk.NSEW)
self.flexx(self.work, r = r)
# Table edit window
self.edit = tk.Toplevel(self.master)
self.edit.transient(self.master)
self.edit.withdraw()
self.edit.title("Table Editor")
self.labelframe = tk.LabelFrame(self.edit, labelanchor = tk.N, text = "Name")
self.labelframe.grid(row = 0, column = 0, sticky = tk.NSEW)
self.flexx(self.edit)
# place entry tools here
self.data = []
for c in range(self.columns):
l = tk.Label(self.labelframe, text = f"{indice[c]}")
l.grid(row = c, column = 0, sticky = tk.NSEW)
e = tk.Entry(self.labelframe)
e.grid(row = c, column = 1, sticky = tk.NSEW)
self.data.append(e)
b = tk.Button(
self.labelframe, text = "Enter", bd = 1,
command = self.redirect(self.change, c))
b.grid(row = c, column = 2, sticky = tk.NSEW)
self.flexx(self.labelframe, r = c, c = 1)
# wire up master and work widgets
for a, b in [(self.master, self.closer),
(self.work, self.opener),
(self.edit, self.editor)]:
a.protocol('WM_DELETE_WINDOW', b)
a.bind("<KeyRelease-Escape>", b)
# Keys to work widget
self.master.bind("<F1>", self.opener)
self.work.bind("<F1>", self.opener)
self.edit.bind("<F1>", self.editor)
def redirect(self, f, *args):
return lambda: f(*args)
def flexx(self, m, r = 0, c = 0, rw = 1, cw = 1):
m.rowconfigure( r, weight = rw )
m.columnconfigure( c, weight = cw )
def change(self, c):
e = self.data[c]
self.store[self.currentRow][c]["text"] = e.get()
table[self.currentRow][c] = e.get()
def closer(self, ev = None):
if messagebox.askquestion(title = "Quit", message = "Confirm",
detail = "Close program?") == "yes":
self.master.destroy()
def opens( self, o, m ):
"""Toggle switch for toplevel"""
if o.winfo_viewable( ):
o.withdraw( )
m.focus_set( )
else:
o.focus_set( )
o.deiconify()
def position(self, o):
x = int(o.winfo_x() + o.winfo_width() + 5)
y = int(o.winfo_y() + o.winfo_height() / 2)
return x, y
def opener(self, ev = None):
x, y = self.position( self.master)
self.work.geometry(f"190x{26*self.rows}+{x}+{y}")
self.opens(self.work, self.master)
def editor(self, ev = None):
x, y = self.position( self.work)
self.edit.geometry(f"213x{26*self.columns}+{x}+{y}")
self.opens(self.edit, self.work)
def access(self, *args):
self.currentRow = r = args[0]
self.labelframe["text"] = f"{table[r][1]}"
for i,e in enumerate(self.data):
e.delete(0, "end")
e.insert(0, table[r][i])
self.editor()
if __name__ == "__main__":
root = tk.Tk()
top = Table(root)
root.mainloop()

Unable to see images using Tkinter Treeview for database processing

I am working on a Database project, running the following code doesn't show the image given. Whole code can be found here.
def populateProducts (self, productName, plist):
rows = self.db.getProductsFromNameNIL(productName)
auximage = Image.open ("/home/sourabh/Documents/Github/DBMS-Lab-Project/TkinterReference/small.png")
self.auxphoto = ImageTk.PhotoImage (auximage)
plist.delete (*plist.get_children ())
for row in rows:
print (row)
plist.insert ('', 'end', text = '#0s text', values = row, image = self.auxphoto)
def browse (self):
browseWin = Tk ()
browseWin.title ("Browse Products")
browseWin.protocol("WM_DELETE_WINDOW", lambda: self.on_closing (browseWin)) # handle window closing
Label(browseWin, text = "Enter product name").grid (row = 0, column = 0, sticky = W)
prodText = StringVar()
Entry(browseWin, textvariable=prodText).grid (row = 0, column = 1, sticky = W)
Button (browseWin, text = 'Switch to Login', command = lambda: self.switchToLogin (browseWin)).grid (row = 20, sticky = W, pady = 4)
############ Product List #############
plist = ttk.Treeview (browseWin)
plist['columns'] = ('pid', 'pname', 'sellerid', 'price', 'tstock', 'pickupaddress', 'description', 'rating')
plist.heading('#0', text = 'Pic directory', anchor = 'center')
plist.column ('#0', anchor = 'w', width = 200)
plist.heading ('pid', text = 'Product ID')
plist.heading ('pname', text = 'Product Name')
plist.heading ('sellerid', text = 'Seller ID')
plist.heading ('price', text = 'Price')
plist.heading ('tstock', text = 'Total Stock')
plist.heading ('pickupaddress', text = 'Pickup Address')
plist.heading ('description', text = 'Description')
plist.heading ('rating', text = 'Rating')
plist['show'] = 'headings'
plist.grid(row = 1, column = 0, rowspan = 18, columnspan = 50)
Button(browseWin, text= 'Search', command= lambda: self.populateProducts (prodText.get (), plist)).grid(row=0, column = 2, sticky=W)
browseWin.mainloop()
In case you want to run the project to test, in that GUI directory run init.sh by typing 'bash init.sh' in terminal and then running 'main.py'. For test, enter details: 'Nikhil' for username and 'hi' for password and select role as 'Customer' and then select 'Enter' and then select 'Browse Products' and enter 'asg'.
Fixed! Issue was with the line
plist['show'] = 'headings'
After removing it, image appears.

Python Status Bar

I am having a problem with adding status bar at the bottom of my program. When I do status.pack() it gives me this error : _tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack. In My (
def init(self): ) If I delete (self.grid(sticky = W+E+N+S) then the window pops up an then the status bar is on the window, but then the rest of the program isn't there. I was wondering if someone give some insight on how to fix this
from tkinter.constants import END
from tkinter import ttk
from tkinter import *
from tkinter import font
from tkinter import messagebox
import tkinter as tk
import turtle
import random
from tkinter import filedialog
from PIL import Image
class App(Frame):
**********************************************************************************************************************************************************************************************************************8888
'''The code below Creates a Menu Bar across the top of the window '''
App = Tk()
menu = Menu (App)
App.config(menu = menu)
'''Lines 20 - 22 are basic setup for drop down meun box at the top of the page.'''
fileMenu = Menu(menu, tearoff = 0)
fileMenu.add_command(label = "New Project", command = turtle)
fileMenu.add_command(label = "Open", command = turtle)
fileMenu.add_command(label = "Save", command = turtle)
fileMenu.add_command(label = "Save as", command = turtle)
fileMenu.add_command(label = "Close", command = turtle)
menu.add_cascade(label = "File", menu = fileMenu)
fileMenu.add_separator()
'''This bit of code adds a separator between the buttons on the drop down menu.'''
fileMenu.add_command(label = "Exit", command = App.quit)
editMenu = Menu(menu, tearoff = 0)
editMenu.add_command(label = "Cut", command = turtle)
editMenu.add_command(label = "Copy", command = turtle)
editMenu.add_command(label = "Paste", command = turtle)
editMenu.add_command(label = "Delete", command = turtle)
editMenu.add_command(label = "Select All", command = turtle)
menu.add_cascade(label = "Edit", menu = editMenu)
helpMenu = Menu(menu, tearoff = 0)
helpMenu.add_command(label = "Help Index", command = turtle)
helpMenu.add_command(label = "About", command = turtle)
menu.add_cascade(label = "Help", menu = helpMenu)
************************************************************************************************************************************************************************************************************************************
''' The code below creates a Status Bar Across the bottom of the page. '''
status = Label(App, text = "This is a status bar...", bd = 1, relief = SUNKEN, anchor = W)
status.pack()
******************************************************************************************************************************************************************************************************************************
def __init__(self):
'''Sets up the window and widgets.'''
Frame.__init__(self, bg = "white" ) #this sets the background color of the window.
self.master.title("Auto Body Buddy Estimator") #this is the title of the screen
self.master.geometry("600x600") #this is the specs for the window size
self.master.resizable(0, 0) #this makes the window none resizable
self.master.columnconfigure(0, weight = 1)
self.master.rowconfigure(0, weight = 1)
self.grid(sticky = W+E+N+S)
#!/usr/bin/python
'''import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
message = ('The file "' + fn + '" was uploaded successfully')
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html>
<body>
<p>%s</p>
</body>
</html>
""" % (message,) '''
***********************************************************************************************************************************************************************
''' Creates the nested frame for the Data pane for the image '''
self._dataPane1 = Frame(self)#, bg = "orange")
self._dataPane1.grid(row = 0, column = 0)
self._pictureImage = PhotoImage(file = "../logo.gif")
self._imageLabel = Label(self._dataPane1, image = self._pictureImage)
self._imageLabel.grid(row = 0, column= 0)
*********************************************************************************************************************************************************************
''' Creates the nested frame for the Data pane'''
self._dataPaneEntryInfo = Frame(self, bg = "white")
self._dataPaneEntryInfo.grid(row = 1, column = 0)
''' Label and field for First Name '''
self._firstNameLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "First Name ")
self._firstNameLabel.grid(row = 0, column = 0)
self._firstNameVar = DoubleVar()
self._firstNameEntry = Entry(self._dataPaneEntryInfo, textvariable = self._firstNameVar)
self._firstNameEntry.grid(row = 0, column = 1)
''' Label and field for Last Name '''
self._LastNameLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Last Name ")
self._LastNameLabel.grid(row = 1, column = 0)
self._LastNameVar = DoubleVar()
self._LastNameEntry = Entry(self._dataPaneEntryInfo, textvariable = self._LastNameVar)
self._LastNameEntry.grid(row = 1, column = 1)
''' Label and field for Phone Number '''
self._phoneNumberLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Phone Number ")
self._phoneNumberLabel.grid(row = 2, column = 0)
self._phoneNumberVar = DoubleVar()
self._phoneNumberEntry = Entry(self._dataPaneEntryInfo, textvariable = self._phoneNumberVar)
self._phoneNumberEntry.grid(row = 2, column = 1)
''' Label and field for Email '''
self._EmailLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Email Address ")
self._EmailLabel.grid(row = 3, column = 0)
self._EmailVar = DoubleVar()
self._EmailEntry = Entry(self._dataPaneEntryInfo, textvariable = self._EmailVar)
self._EmailEntry.grid(row = 3, column = 1)
''' Label and field for Address '''
self._addressLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Address \n (OPITIONAL) ")
self._addressLabel.grid(row = 4, column = 0)
self._addressVar = DoubleVar()
self._addressEntry = Entry(self._dataPaneEntryInfo, textvariable = self._addressVar)
self._addressEntry.grid(row = 4, column = 1)
*********************************************************************************************************************************************************************
''' Label and field for Year of the Car '''
self._yearLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Year ")
self._yearLabel.grid(row = 0, column = 2)
self._yearVar = DoubleVar()
self._yearEntry = Entry(self._dataPaneEntryInfo, textvariable = self._yearVar)
self._yearEntry.grid(row = 0, column = 3)
''' Label and field for Make of the Car '''
self._makeLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Make ")
self._makeLabel.grid(row = 1, column = 2)
self._makeVar = DoubleVar()
self._makeEntry = Entry(self._dataPaneEntryInfo, textvariable = self._makeVar)
self._makeEntry.grid(row = 1, column = 3)
''' Label and field for Model of the Car '''
self._modelLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Model ")
self._modelLabel.grid(row = 2, column = 2)
self._modelVar = DoubleVar()
self._modelEntry = Entry(self._dataPaneEntryInfo, textvariable = self._modelVar)
self._modelEntry.grid(row = 2, column = 3)
''' Label and field for Package of the Car '''
self._packageLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "Package ")
self._packageLabel.grid(row = 3, column = 2)
self._packageVar = DoubleVar()
self._packageEntry = Entry(self._dataPaneEntryInfo, textvariable = self._packageVar)
self._packageEntry.grid(row = 3, column = 3)
''' Label and field for VIN # of the Car '''
self._vinLabel = Label(self._dataPaneEntryInfo, bg = "white", text = "VIN # ")
self._vinLabel.grid(row = 4, column = 2)
self._vinVar = DoubleVar()
self._vinEntry = Entry(self._dataPaneEntryInfo, textvariable = self._vinVar)
self._vinEntry.grid(row = 4, column = 3)
******************************************************************************************************************************************************************************************************
''' Creates the nested frame for the Data pane'''
self._dataPaneComment = Frame(self, bg = "black")
self._dataPaneComment.grid(row = 2, column = 0)
'''# Label and info field for Comment Box .'''
self._text = "Enter text here. "
self._outputArea = Text(self._dataPaneComment, width = 50, height = 10, wrap = WORD)
self._outputArea.grid(row = 0, column = 0, columnspan = 2)
*********************************************************************************************************************************************************************************************************
''' Creates the nested frame for the Button pane for the Submit'''
self._buttonPane = Frame(self) #this creates a box for the buttons to be placed in one area.
self._buttonPane.grid(row = 3, column = 0)#this gives the button pane a position in the GUI
''' Black and White button '''
self._button1 = Button(self._buttonPane, text = "SUBMIT", command = self._NameEntry)#This creates the button.
self._button1.grid(row = 0, column = 0) #This gives the button a position in the GUI.
********************************************************************************************************************************************************************************************************
def _NameEntry(self):
open("Results.txt", "w").close()
first = self._firstNameEntry.get()
last = self._LastNameEntry.get()
phone = self._phoneNumberEntry.get()
email = self._EmailEntry.get()
address = self._addressEntry.get()
year = self._yearEntry.get()
make = self._makeEntry.get()
model = self._modelEntry.get()
package = self._packageEntry.get()
vin = self._vinEntry.get()
with open("../" + first + " " + last + ".txt", "a") as the_file:
the_file.write("First Name: " + first + "\n" "Last Name: " + last + "\n" "Phone Number: " + phone + "\n" "Email: " + email + "\n"
"Address: " + address + "\n" "Year: " + year + "\n" "Make: " + make + "\n" "Model: " + model + "\n"
"Package: " + package + "\n" "Vin: " + vin + "\n")
'''open("Results.txt", "w").close()
last = self._LastNameEntry.get()
with open("../Results.txt", "a") as the_file:
the_file.write("Last Name: " + last)'''
'''first = self._firstNameEntry.get()
name = open("Results.txt", "w")
name.write("First Name: ".insert(first))
name.close()'''
def main():
'''Instantiate and pop up the window.'''
App().mainloop()
if __name__ == '__main__':
main()
I'm exactly sure on how to upload the gif file with this code.
The error message is telling you what's wrong. If you have already used one geometry manager within a widget you cannot use another.
e.g. - You cannot use both pack and grid within a frame. You must use one or the other.
You could make another widget and then use the seperate geometry manager within this widget but you would have to use the original manager to place it within the master widget.

Python Gui not responding to database

The purpose of this post is to determine the error within the code, I have spent countless hours trying to alter the code to see what the error is. I am trying to add a employee to a database through a python GUI (tkinter). Currently it is only inserting " " information, this is checked within our the def delete with a print statement. A similar problem I am having with def delete however the information in the tuple is not displaying in a listBox. Does anyone have a solution to why these faults are occurring?
def addEmp():
top = Toplevel()
top.title("Add Employee")
top.geometry("470x385")
app = Frame(top)
app.grid()
firstName = StringVar()
lastName = StringVar()
address = StringVar()
payRate = StringVar()
inUnion = StringVar()
paymentMethod = StringVar()
grp1 = StringVar()
firstNameLabel = Label (app, text = "First Name:", font = 15)
firstNameLabel.grid(row = 0, column = 0)
firstNameEntry = Entry (app, text = "", textvariable = firstName)
firstNameEntry.grid(row = 0, column = 1)
surNameLabel = Label (app, text = "Surname:", font = 15)
surNameLabel.grid(row = 1, column = 0)
lastNameEntry= Entry (app, text = "", textvariable = lastName)
lastNameEntry.grid(row = 1, column = 1)
addressLabel = Label (app, text = "Address:", font = 15)
addressLabel.grid(row = 2, column = 0)
addressEntry = Entry (app, text = "", textvariable = address)
addressEntry.grid(row = 2, column = 1)
payRateLabel = Label (app, text = "Pay Rate Hourly:", font = 15)
payRateLabel.grid(row = 3, column = 0)
payRateEntry = Entry (app, text = "", textvariable = payRate)
payRateEntry.grid(row = 3, column = 1)
salaryLabel = Label (app, text = "Pay Rate Monthly:", font = 15)
salaryLabel.grid(row = 4, column = 0)
salaryEntry = Entry (app, text = "")
salaryEntry.grid(row = 4, column = 1)
payTypeLabel = Label (app, text = "Work Type:", font = 15)
payTypeLabel.grid(row = 5, column = 0)
radio1 = Radiobutton(app, text = "Full Time (Monthly Salary)", value = 'Monthly', variable = grp1)
radio1.grid(row = 6, column = 1)
radio2 = Radiobutton(app, text = "Part Time (Hourly Pay per Week)", value = 'Weekly', variable = grp1)
radio2.grid(row = 7, column = 1)
radio3 = Radiobutton(app, text = "Commission", value = 'Commission', variable = grp1)
radio3.grid(row = 8, column = 1)
paymentOptionsLabel = Label (app, text = "Payment Option:", font = 15)
paymentOptionsLabel.grid(row = 9, column = 0)
radio4 = Radiobutton(app, text = "Mail to current address", value = "Mail", variable = paymentMethod)
radio4.grid(row = 10, column = 1)
radio5 = Radiobutton(app, text = "Held by Paymaster", value = "Hold", variable = paymentMethod)
radio5.grid(row = 11, column = 1)
radio6 = Radiobutton(app, text = "Directly Deposit into bank account", value = "Bank", variable = paymentMethod)
radio6.grid(row = 12, column = 1)
unionLabel = Label (app, text = "Union:", font = 15)
unionLabel.grid(row = 13, column = 0)
radio1union = Radiobutton(app, text = "Yes", value = '1', variable = inUnion)
radio1union.grid(row = 14, column = 1)
radio2union = Radiobutton(app, text = "No", value = '0', variable = inUnion)
radio2union.grid(row = 15, column = 1)
submitButton = Button (app, command = addEmpSubmit, text = "Submit", font = 15)
submitButton.grid(row = 20, column = 3)
def addEmpSubmit():
c.execute("INSERT INTO employees (first_name, last_name, address, in_union, pay_type, payment_method) VALUES (?, ?, ?, ?, ?, ?)",
(str(firstName), str(lastName), str(address), str(inUnion), str(payType), str(paymentMethod)))
connection.commit()
if payType == "Weekly":
c.execute("UPDATE employees SET pay_rate=? WHERE employee_id=?", (payRate, c.lastrowid))
connection.commit()
elif payType == "Monthly":
c.execute("UPDATE employees SET monthly_salary=? WHERE employee_id=?", (monthlySalary, c.lastrowid))
connection.commit()
elif payType == "Commission":
c.execute("UPDATE employees SET monthly_salary=?, commission_rate=? WHERE employee_id=?",
(monthlySalary, commissionRate, c.lastrowid))
connection.commit()
def deleteEmp():
top = Toplevel()
top.title("Delete Employee")
top.geometry("470x385")
deleteList = Listbox(app)
deleteList.grid(row = 0, column = 0)
listItem = ""
c.execute("SELECT * FROM employees")
allEmp = c.fetchall()
for line in allEmp:
for item in line:
print(str(item))
listItem += str(item)
deleteList.insert(END, listItem)
connection.commit()
empIDLabel = Label (app, text = "Please select an Emp ID:", font = 15)
empIDLabel.grid(row = 1, column = 0)
empIDEntry = Entry (app, text = "")
empIDEntry.grid(row = 2, column = 0)
deleteButton = Button (app, text = "Delete", font = 15)
deleteButton.grid(row = 2, column = 1)
Read properly the documentation on ControlVariables / StringVar.
The values you provide for INSERT INTO - queries are not the values of the entry widgets.
>>> name=tk.StringVar()
>>> name.set("First Name")
>>> name
<Tkinter.StringVar instance at 0x01EB4CB0>
>>> str(name)
'PY_VAR0'
>>> name
<Tkinter.StringVar instance at 0x01EB4CB0>
>>> name.get()
'First Name'
Please make sure you post only code samples that can reproduce your error on (at least) your system. As for this reason it is very hard to reproduce the issues you have got.
Split your code up and debug it in smaller slices. Check the different components on their own (e.g. first the sql part with some dummy data but using variables, StringVars, etc.).
Do you receive any error messages? If so, please add them to your post so that we can see if you are struggling at a certain point. Something like - "my code is not working - why?" is hard to analyze if even possible with correct information.

Unable to link Classes and Tkinter in python 3.2

This is my code:
from tkinter import *
class Car:
def __init__(self, car_id, name, num_seats, available):
self.car_id = car_id
self.name = name
self.num_seats = num_seats
self.available = available
available_cars.append(self.name)
def hire_car(self):
self.available = False
booked_cars.append(self.name)
available_cars.remove(self.name)
def return_car(self):
self.available = True
booked_cars.remove(self.name)
available_cars.append(self.name)
def display():
pass
class Carlist:
def __init__(self, available_cars):
self.available_cars = available_cars
def addCar():
pass
def displayAvailable():
print(available_cars)
def displayBooked():
print(booked_cars)
booked_cars = []
available_cars = []
Car(1,"Suzuki Van", 2, True)
id2 = Car(2,"Toyota Corolla", 4, True)
id3 = Car(3,"Honda Crv", 4, True)
id4 = Car(4,"Suzuki Swift", 4, True)
id5 = Car(5,"Mitsibishi Airtrek", 4, True)
id6 = Car(6,"Nissan DC Ute", 4, True)
id7 = Car(7,"Toyota Previa", 7, True)
Car.hire_car(id3)
Carlist.displayAvailable()
Carlist.displayBooked()
#Interface Code
root = Tk()
root.title("Car Booking System")
frameTop = Frame(root)
frameLeft = Frame(root)
frameRight = Frame(root)
frameBottom = Frame(root)
#Top
topLabel = Label(frameTop, text = "Car Booking System", font = 20).pack()
#Right Side
bookLabel = Label(frameRight, text = "Book:").pack()
varSelectedCar = StringVar()
varSelectedCar.set(available_cars[0])
optionHire = OptionMenu(frameRight, varSelectedCar, *available_cars).pack()
buttonHireCar = Button(frameRight, text = "Enter", command = Car.hire_car).pack()
#Left Side
returnLabel = Label(frameLeft, text = "Return:").pack()
varSelectedCar2 = StringVar()
varSelectedCar2.set(booked_cars[0])
optionReturn = OptionMenu(frameLeft, varSelectedCar2, *booked_cars).pack()
buttonHireCar2 = Button(frameLeft, text = "Enter", command = Car.hire_car).pack()
#Bottom
summaryLabel = Label(frameBottom, text = "Summary:").pack()
#INITIALISATION
frameTop.pack(side = TOP)
frameLeft.pack(side = LEFT)
frameRight.pack(side = RIGHT)
frameBottom.pack(side = BOTTOM)
root.mainloop()
I am trying to link the lists to the GUI interface so when enter is clicked it either runs hire_car or return_car and adds their name to the relevant list. Any idea how to do this? Help would be much appreciated.
The overall idea is to have a program which can book and return cars and as a summary at the bottom....
Although this site is not to make other's homework, you got lucky today. However, please try to figure out how it works. How to update OptionMenu info is from HERE.
from collections import namedtuple
from tkinter import *
Car = namedtuple('Car', 'name num_seats')
class CarList:
ID = 0
def __init__(self):
self.cars, self.hired = {}, set()
def add_car(self, car):
self.cars[self.ID] = car
self.ID += 1
def available_cars(self):
'''Returns the list of (id, Car) tuples sorted by Car.'''
return sorted(((car, id)
for id, car in self.cars.items()
if id not in self.hired))
#staticmethod
def labels(cars_seq):
return ['{} [{}]'.format(t[0].name, t[1])
for t in cars_seq]
def hire_car(self, id):
if id in self.hired:
raise ValueError('That car is already hired.')
self.hired.add(id)
def hired_cars(self):
return sorted(((self.cars[id], id)
for id in self.hired))
def return_car(self, id):
if id not in self.hired:
raise ValueError('That car is not even hired.')
self.hired.remove(id)
def add_car(car):
if not isinstance(car, Car):
raise TypeError('Invalid car object.')
carlist.add_car(car)
update_optionmenus()
def hire_car():
label = opt_hire.var.get()
if label:
id = int(label.rsplit(maxsplit=1)[-1][1:-1])
carlist.hire_car(id)
update_optionmenus()
def return_car():
label = opt_return.var.get()
if label:
id = int(label.rsplit(maxsplit=1)[-1][1:-1])
carlist.return_car(id)
update_optionmenus()
def _update_optionmenu(opt_menu_widget, car_seq):
cars = carlist.labels(car_seq)
if cars:
opt_menu_widget.var.set(cars[0])
else:
opt_menu_widget.var.set('')
opt_menu_widget['menu'].delete(0, END)
for lab in cars:
opt_menu_widget['menu'].add_command(label=lab,
command=lambda lab=lab: opt_menu_widget.var.set(lab))
def update_optionmenus():
_update_optionmenu(opt_hire, carlist.available_cars())
_update_optionmenu(opt_return, carlist.hired_cars())
# You have to initiate a carlist to make it work.
carlist = CarList()
#Interface Code
root = Tk()
root.title('Car Booking System')
frame_top = Frame(root)
frame_top.pack(side = TOP)
frame_left = Frame(root)
frame_left.pack(side = LEFT)
frame_right = Frame(root)
frame_right.pack(side = RIGHT)
frame_bottom = Frame(root)
frame_bottom.pack(side = BOTTOM)
#Top
label_top = Label(frame_top, text = 'Car Booking System',
font = 20).pack()
#Right Side
label_hire = Label(frame_right, text = 'Book:', width=25).pack()
gui_var_hire = StringVar()
opt_hire = OptionMenu(frame_right, gui_var_hire, 'anything')
opt_hire.var = gui_var_hire
del gui_var_hire
opt_hire.pack()
button_hire = Button(frame_right, text = 'Enter',
command = hire_car).pack()
#Left Side
label_return = Label(frame_left, text = 'Return:', width=25).pack()
gui_var_return = StringVar()
opt_return = OptionMenu(frame_left, gui_var_return, 'anything')
opt_return.var = gui_var_return
opt_return.pack()
del gui_var_return
button_return = Button(frame_left, text = 'Enter',
command = return_car).pack()
#Bottom
label_summary = Label(frame_bottom, text = 'Summary:').pack()
add_car(Car('Suzuki Van', 2))
add_car(Car('Toyota Corolla', 4))
add_car(Car('Honda Crv', 4))
add_car(Car('Suzuki Swift', 4))
add_car(Car('Mitsibishi Airtrek', 4))
add_car(Car('Nissan DC Ute', 4))
add_car(Car('Toyota Previa', 7))
add_car(Car('Honda Crv', 2))
root.mainloop()

Categories

Resources