I am using Python 3.x, and I'm trying to fetch Dataset records and display them in an extra Window. I'm a bloody beginner and currently I don't see my error. I've checked multiple threads but didn't get the solution. Debugging isn't helping me either.
Here's my approach:
import sqlite3
from tkinter import *
class Overview():
def __init__(self,master):
self.master = master
self.master.geometry('170x110+100+200')
self.master.title('Welcome!')
self.button1 = Button(self.master, text="Show dataset", fg='green', command=self.gotoMenu).grid(
row=1, column=1)
def gotoMenu(self):
# This is the Dataset GUI#
root2 = Toplevel(self.master)
myGUI = Menu(root2)
def main():
root = Tk()
overviewGUI = Overview(root)
root.mainloop()
if __name__ == '__main__':
main()
class Menu:
def __init__(self,master):
# This is the Dataset GUI#
self.connection = sqlite3.connect('test.db')
print("Opened database successfully")
self.cur = self.connection.cursor()
self.master = master
self.master.title('Dataset')
self.master.geometry("320x240")
print("GUI created")
self.dateLabel = Label(self.master, text="Date", width=10)
self.dateLabel.grid(row=0, column=0)
self.BMILabel = Label(self.master, text="Name", width=10)
self.BMILabel.grid(row=0, column=1)
self.stateLabel = Label(self.master, text="ID", width=10)
self.stateLabel.grid(row=0, column=2)
self.insertDS('random')
self.showallrecords()
def showallrecords(self):
data = self.readfromdatabase()
for index, dat in enumerate(data):
Label(self.master, text=dat[2]).grid(row=index + 1, column=0)
Label(self.master, text=dat[1]).grid(row=index + 1, column=1)
Label(self.master, text=dat[0]).grid(row=index + 1, column=2)
def readfromdatabase(self):
self.cur.execute("SELECT * FROM LOGGING")
return self.cur.fetchall()
def createTable(self):
try:
self.connection.execute(
"CREATE TABLE LOGGING(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT NOT NULL, TIMESTAMP DATE DEFAULT (datetime('now','localtime')));")
print("Table created successfully")
except:
print("Table already exists")
def insertDS(self, name):
self.connection.execute("INSERT INTO LOGGING (NAME) \
VALUES (?);", [name])
self.connection.commit()
print("Records created successfully")
My Application should start with the "Overview" GUI, on button click I want to see all fetched Datasets from "Menu" Class.
However, after clicking the button the next window is empty and has the title "Welcome" which should be "Dataset"
UPDATE:
I am getting no error, BUT my fetched results won't show in the 2nd Window, and the title isn't self.master.title('Dataset') as initialized in class Menu.
I feel like it's just creating some empty Window without even looking in my Menu Class?
Solution:
python className not defined NameError
Somehow(can't explain why) when I moved the ´name´ block down with the def (even though indentions were right) it worked.
You have overloaded Menu, change your class name by an another name.
And don't use import *
Related
I apologize upfront if there is another discussion that already addresses this issue, but I could not find anything. I am new to Python (and for that matter programming other than a little bit of Pascal back in the 90's).
I am building a GUI with tk Entry boxes for a user to enter values, which is then stored in a sqlite db. I would like the user to be able to click on the values from one of the fields in a listbox, which would then re-populate the tk Entry boxes with the values for all fields for the selected record. I have been able to make this work, but it only works on the second click as I bind the list box to the function to populate the tk Entry boxes on Button-1. The first click generates the following error, which I have seen references to in other questions, but I cannot translate those answers to my situation:
Error:
Traceback (most recent call last):
File "...\Python\Python38-32\lib\tkinter__init__.py", line 1883, in call
return self.func(*args)
File "fe.py", line 108, in selectitem
selecteditem.append(lb1.get(ndex))
File "...\Python\Python38-32\lib\tkinter__init__.py", line 3182, in get
return self.tk.call(self._w, 'get', first)
_tkinter.TclError: bad listbox index "": must be active, anchor, end, #x,y, or a number
Here is example code that replicates the error - to use, first add a a couple of values through the Setup -> Items menu by filling in the VAL and REF boxes and clicking the Add Item button. Then click on one of the items in the list box. The first click should generate the error above. When you click a second time the Entry boxes should populate:
```
import sqlite3
import itertools
import tkinter as tk
from tkinter import ttk
INTRO_FONT = ("Arial", 72)
LARGE_FONT = ("Arial", 12)
NORMAL_FONT = ("Arial", 10)
SMALL_FONT = ("Arial", 8)
#Function to create database
def create_db():
conn = sqlite3.connect("demo.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS demotable (id INTEGER PRIMARY KEY, val TEXT, ref TEXT)")
conn.commit()
conn.close()
#Create database
create_db()
#Main Class to manage frames
class demo(tk.Tk):
def __init__(self,*args,**kwargs):
tk.Tk.__init__(self,*args,**kwargs)
container = tk.Frame(self)
container.pack(side="top",fill="both",expand=True)
container.grid_rowconfigure(0,weight=1)
container.grid_columnconfigure(0,weight=1)
menubar = tk.Menu(container)
filemenu = tk.Menu(menubar,tearoff=0)
filemenu.add_command(label="Exit", command=quit)
menubar.add_cascade(label="File", menu=filemenu)
setupmenu = tk.Menu(menubar, tearoff=0)
setupmenu.add_command(label="Items",command = lambda: self.show_frame(Itemsetuppage))
menubar.add_cascade(label="Setup", menu=setupmenu)
tk.Tk.config(self, menu=menubar)
self.frames={}
for F in (Itemsetuppage,Itemsetuppage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(Itemsetuppage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
# Frame that inserts and loads values
class Itemsetuppage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#Function to populate listbox with values
def popitemlist(self):
lb1.delete(0, tk.END)
for item in itemlist():
lb1.insert(tk.END, item)
#Function to add new item to database
def additem():
additem_db(val.get(), ref.get())
val_entry.delete(0, 'end')
ref_entry.delete(0, 'end')
popitemlist(self)
#Function used to populate tk.Entry boxes from database when item in listbox is clicked
def selectitem(event):
global selecteditem
selecteditem = []
ndex = lb1.curselection()
selecteditem.append(lb1.get(ndex))
itemquery = select_item(selecteditem)
val_entry.delete(0, 'end')
val_entry.insert(0, itemquery[1])
ref_entry.delete(0, 'end')
ref_entry.insert(0, itemquery[2])
#Function to query database for values to populate lb1
def itemlist():
conn = sqlite3.connect("demo.db")
cur = conn.cursor()
cur.execute("SELECT DISTINCT val FROM demotable")
results = cur.fetchall()
itemlist = list(itertools.chain(*results))
conn.commit()
conn.close()
return itemlist
#Function to insert values from tk.Entry boxes to database
def additem_db(val, ref):
conn = sqlite3.connect("demo.db")
cur = conn.cursor()
cur.execute("INSERT OR IGNORE INTO demotable VALUES (NULL, ?, ?)",(val,ref))
conn.commit()
conn.close()
#Function to query database for individual record to populate tk.Entry boxes when item is clicked in lb1
def select_item(val):
conn = sqlite3.connect("demo.db")
cur = conn.cursor()
cur.execute("SELECT * FROM demotable WHERE val=?",(val))
results = cur.fetchall()
itemdetail = list(itertools.chain(*results))
conn.commit()
conn.close()
return itemdetail
l1 = tk.Label(self, text="Values in database:")
l1.grid(row=0, column=0, padx=5, pady=5)
lb1 = tk.Listbox(self, selectmode=tk.SINGLE)
lb1.grid(row=1, column=0, padx=5, pady=5)
popitemlist(self)
lb1.bind("<Button-1>", selectitem)
l2 = tk.Label(self, text="Type val into entry box to store:")
l2.grid(row=0, column=1, padx=5, pady=5)
val = tk.StringVar(self)
val_entry = tk.Entry(self, textvariable=val)
val_entry.grid(row=0, column=2, padx=5, pady=5)
l2 = tk.Label(self, text="Type ref into entry box to store:")
l2.grid(row=1, column=1, padx=5, pady=5)
ref = tk.StringVar(self)
ref_entry = tk.Entry(self, textvariable=ref)
ref_entry.grid(row=1, column=2, padx=5, pady=5)
b1 = tk.Button(self, text="Add item",command=additem)
b1.grid(row=2, column=2, padx=5, pady=5)
app = demo()
app.geometry("480x240")
app.mainloop()
```
Thank you & apologies if my code offends anyone!
Not having run your code as I have no sqlite3 database I may be way off, but listbox generates a virtual event when a value is selected <<ListboxSelect>> which you can bind to. Try replacing:
lb1.bind("<Button-1>", selectitem)
with
lb1.bind("<<ListboxSelect>>", selectitem)
Also, I think lb1.curselection() returns a tuple..., try printing it and see what you get. In the code I checked I always do lb1.curselection()[0].
I'm trying to setup a program where my tkinter GUI functions are in a class and my database functions are in another class. I have a function external to both classes that fails when I try to call a function within the DB class. Can you help me resolve this error? Should both my GUI and any database be in separate functions or is that a poor design. The attached code is a stripped down version to illustrates my issue. Clicking the "View all" button generates the error.
import sqlite3
from tkinter import *
from tkinter import messagebox
class DB:
def __init__(self):
self.conn = sqlite3.connect("mybooks.db")
self.cur = self.conn.cursor()
self.cur.execute(
"CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title TEXT, author TEXT, isbn INTEGER)")
self.conn.commit()
def __del__(self):
self.conn.close()
def view(self):
self.cur.execute("SELECT * FROM book")
rows = cur.fetchall()
return rows
def view_command():
# there is a problem with the next line
# when rows=DB.view() error is TypeError: view() missing 1 required positional argument: 'self'
# when rows=DB.view(self) error is NameError: name 'self' is not defined
rows=DB.view(self)
for row in rows:
print(row)
class App_GUI(): # create the main window
def __init__(self, master):
self.master = master
self.master.title("My Books")
self.master.l1 = Label(self.master, text="Title")
self.master.l1.grid(row=0, column=0)
self.master.l2 = Label(self.master, text="Author")
self.master.l2.grid(row=0, column=2)
self.master.l3 = Label(self.master, text="ISBN")
self.master.l3.grid(row=1, column=0)
self.master.title_text = StringVar()
self.master.e1 = Entry(self.master, textvariable=self.master.title_text)
self.master.e1.grid(row=0, column=1)
self.master.author_text = StringVar()
self.master.e2 = Entry(self.master, textvariable=self.master.author_text)
self.master.e2.grid(row=0, column=3)
self.master.isbn_text = StringVar()
self.master.e3 = Entry(self.master, textvariable=self.master.isbn_text)
self.master.e3.grid(row=1, column=1)
self.master.list1 = Listbox(self.master, height=6, width=35)
self.master.list1.grid(row=2, column=0, rowspan=6, columnspan=2)
self.master.sb1 = Scrollbar(self.master)
self.master.sb1.grid(row=2, column=2, rowspan=6)
self.master.list1.configure(yscrollcommand=self.master.sb1.set)
self.master.sb1.configure(command=self.master.list1.yview)
self.master.b1 = Button(self.master, text="View all", width=12, command=view_command)
self.master.b1.grid(row=2, column=3)
self.master.b6 = Button(self.master, text="Close", width=12, command=self.master.destroy)
self.master.b6.grid(row=7, column=3)
return
###############################
# Program Main #
###############################
def main():
db = DB()
root = Tk()
def on_closing():
dd = db
if messagebox.askokcancel("Quit", "Do you want to close the application"): # ask the user if he/she wants to close the application
root.destroy()
del dd
root.protocol("WM_DELETE_WINDOW", on_closing) # catch the user closing the window
app = App_GUI(root) # creation of an instance
root.mainloop() # tkinter mainloop
if __name__ == '__main__':
main()
````
You need to pass db to App_GUI and then on to the function:
def view_command(db):
rows = db.view()
for row in rows:
print(row)
class App_GUI(): # create the main window
def __init__(self, master, db):
# other stuff elided ...
self.master.b1 = Button(self.master, text="View all", width=12, command=lambda : view_command(db))
...
def main():
db = DB()
# other stuff elided
app = App_GUI(root, db)
edit: forgot to remove self.
I figured it out! In addition to your changes, I had to remove 'self' from rows=db.view(). Thanks for your help! Revised code:
import sqlite3
from tkinter import *
from tkinter import messagebox
class DB:
def __init__(self):
self.conn = sqlite3.connect("mybooks.db")
self.cur = self.conn.cursor()
self.cur.execute(
"CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title TEXT, author TEXT, isbn INTEGER)")
self.conn.commit()
def __del__(self):
self.conn.close()
def view(self):
self.cur.execute("SELECT * FROM book")
rows = self.cur.fetchall()
return rows
def view_command(db):
rows=db.view()
for row in rows:
print(row)
class App_GUI(): # create the main window
def __init__(self, master, db):
self.master = master
self.master.title("My Books")
self.master.l1 = Label(self.master, text="Title")
self.master.l1.grid(row=0, column=0)
self.master.l2 = Label(self.master, text="Author")
self.master.l2.grid(row=0, column=2)
self.master.l3 = Label(self.master, text="ISBN")
self.master.l3.grid(row=1, column=0)
self.master.title_text = StringVar()
self.master.e1 = Entry(self.master, textvariable=self.master.title_text)
self.master.e1.grid(row=0, column=1)
self.master.author_text = StringVar()
self.master.e2 = Entry(self.master, textvariable=self.master.author_text)
self.master.e2.grid(row=0, column=3)
self.master.isbn_text = StringVar()
self.master.e3 = Entry(self.master, textvariable=self.master.isbn_text)
self.master.e3.grid(row=1, column=1)
self.master.list1 = Listbox(self.master, height=6, width=35)
self.master.list1.grid(row=2, column=0, rowspan=6, columnspan=2)
self.master.sb1 = Scrollbar(self.master)
self.master.sb1.grid(row=2, column=2, rowspan=6)
self.master.list1.configure(yscrollcommand=self.master.sb1.set)
self.master.sb1.configure(command=self.master.list1.yview)
self.master.b1 = Button(self.master, text="View all", width=12, command=lambda : view_command(db))
self.master.b1.grid(row=2, column=3)
self.master.b6 = Button(self.master, text="Close", width=12, command=self.master.destroy)
self.master.b6.grid(row=7, column=3)
return
###############################
# Program Main #
###############################
def main():
db = DB()
root = Tk()
def on_closing():
dd = db
if messagebox.askokcancel("Quit", "Do you want to close the application"): # ask the user if he/she wants to close the application
root.destroy()
del dd
root.protocol("WM_DELETE_WINDOW", on_closing) # catch the user closing the window
app = App_GUI(root, db) # creation of an instance
root.mainloop() # tkinter mainloop
if __name__ == '__main__':
main()
I'm having some trouble creating an entry widget with tkinter. I've imported the necessary modules and have already created several buttons and check boxes. However I cannot figure out how to properly initialize the Entry. Here is my relevant code:
# Necessary Modules.------------------------------------------------------------
import win32com.client as win32
import re
from tkinter import *
from tkinter.filedialog import askopenfilename
import tkinter.messagebox
# Class for selecting the file.-------------------------------------------------
class FilenameClass():
def __init__(self):
self.location = 'User Import.txt'
def getFile(self, identity):
self.file_opt = options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('Text Document (.txt)', '.txt'),
('all files', '.*')]
self.filename = askopenfilename(**self.file_opt)
if self.filename:
if 'User Import' in identity:
self.location = self.filename
app.get_txt_File['bg'] = '#0d0'
user_file = open(self.filename, 'r')
user_total = user_file.read()
remove_lines = user_total.splitlines()
for user in remove_lines:
regex_tab = re.compile('\\t')
user_info = regex_tab.split(user)
app.users.append(user_info)
else:
app.loadButton['bg'] = '#e10'
# Main Class.-------------------------------------------------------------------
class Application(Frame, Tk):
def __init__(self, master=None):
Frame.__init__(self, master)
self.users = []
self.fileOBJtxt = FilenameClass()
self.createWidgets()
def createWidgets(self):
# Define the default values for the options for the buttons
# Grid layout options
self.rowconfigure(0, minsize=5)
self.width = 54
self.grid(padx=5)
self.loadButton_gopt = {'row':1,'column':1,'padx': 2, 'pady': 5}
self.loadButton_wopt = {'width': round(self.width),'bg':'#e10'}
self.loadButton()
self.trainingCheckBox()
self.signatureInput()
def loadButton(self):
'''Button that calls the filename class which allows the user to select
the text file they wish to use.'''
self.get_txt_File = Button(self, text="Load User List", \
command=lambda: self.fileOBJtxt.getFile('User Import'))
for key, value in self.loadButton_wopt.items():
self.get_txt_File[key] = value
self.get_txt_File.grid(**self.loadButton_gopt)
def trainingCheckBox(self):
self.training_var = IntVar()
self.training = Checkbutton(text="Include training video?", \
variable=self.training_var).grid(row=2, sticky=W)
def signatureInput(self):
Label(text="Signature Name").grid(row=4, sticky=W)
entry = Entry(bg='#fff', width=50)
entry.grid(row=4, column=1, columnspan=4)
# Initialization parameters.----------------------------------------------------
if __name__ == '__main__':
app = Application()
app.master.title('User Notification Tool')
app.master.geometry('405x550+100+100')
app.master.resizable(width=False, height=False)
app.mainloop()
I'm not seeing any tracebacks, but I can't seem to get my Entry box to show up. What am I doing wrong?
EDIT: added entire code.
The problem with your entry field is you have not told it what frame/window to be placed in.
Change:
entry = Entry(bg='#fff', width=50)
To:
entry = Entry(self, bg='#fff', width=50)
Make sure you always provide the window/frame that a widget is going to be placed in as the first argument. In this case it is self as self refers to a frame.
Keep in mind that your program will not be able to get() the string inside of your entry field because you have not defined it as a class attribute. So most likely you will need to change
This:
entry = Entry(bg='#fff', width=50)
entry.grid(row=4, column=1, columnspan=4)
To This:
self.entry = Entry(self, bg='#fff', width=50)
self.entry.grid(row=4, column=1, columnspan=4)
This change will be necessary in order for the rest of your application to be able to read or write to the entry widget.
Change
entry = Entry(bg='#fff', width=50)
to
entry = tk.Entry(bg='#fff', width=50)
I am having trouble outputting my SQL queries properly. I have posted this earlier but I don't think I explained it very well. I am using an entry widget for at least 10 rows in a SQL query.
The program can search for a first name or last name and provide a list of names tied to the search criteria.
It should only list the name in relation to the present query.
Right now, if you enter a name, it will list all the people that have the same name. Then if you do a second search, it will list the new name plus the previous names you searched for. I am trying to figure out how to properly clear it so that the previous names will no longer show.
I am attaching a screen shot of 3 searches from a database of random names.
The first search is for the first name Burney. There is only one Burney in my database so it lists that one Burney.
Second, Josh is searched for. There are probably around 20 Josh's in the datbase so it overwrites Burney and lists Josh names.
Third, Burney is search for again.
Well, it only overwrites the top Entry row with Burney but leaves all of the previous Josh names.
I only want it to show Burney.
I have played with self.myentry.delete(0, END) in the results[x] but I am not sure if I am using it properly. Or if it would even help my situation.
Attached is a screenshot and a short version of my code:
import os
import pypyodbc
import tkinter
from tkinter import ttk
from tkinter import messagebox
from tkinter import BOTH, END, LEFT
class Adder(ttk.Frame):
"""The adders gui and functions."""
def __init__(self, parent, *args, **kwargs):
ttk.Frame.__init__(self, parent, *args, **kwargs)
self.root = parent
self.init_gui()
def calculate(self):
firstname = str(self.first_entry.get())
lastname = str(self.last_entry.get())
if (firstname and not lastname): # "You entered first name."
try:
connection = pypyodbc.connect('Driver={SQL Server};Server=MYSERVERNAME;Database=MYDATABASE;Trusted_Connection=yes;')
except pypyodbc.Error as ex:
sqlstate = ex.args[0]
if sqlstate == '28000':
self.answer_label['text'] = "You do not have access."
cursor = connection.cursor()
SQLCommand = ("SELECT LASTNAME, FIRSTNAME "
"FROM dbo.MYTABLENAMEHERE " # table name
"with (nolock)"
"WHERE FIRSTNAME = ?")
Values = [firstname]
cursor.execute(SQLCommand,Values)
results = cursor.fetchmany(10)
if results:
self.output0.delete(0, END)
self.output0.insert(0,results[0])
self.output1.insert(0,results[1])
self.output2.insert(0,results[2])
self.output3.insert(0,results[3])
self.output4.insert(0,results[4])
connection.close()
def init_gui(self):
"""Builds GUI."""
self.root.title('Verify')
self.root.option_add('*tearOff', 'FALSE')
self.grid(column=0, row=0, sticky='nsew') # this starts the entire form
# Input Boxes and Button
self.first_entry = tkinter.Entry(self, width=28) # first input box
self.first_entry.grid(sticky='', column=1, row=1)
self.last_entry = tkinter.Entry(self, width=28) # second input box
self.last_entry.grid(sticky='', column=2, row=1)
self.calc_button = ttk.Button(self, text='Search', command=self.calculate) # button
self.calc_button.grid(column=4, row=1, columnspan=1, sticky='w', padx=14)
# Output entries for answers
self.output0 = tkinter.Entry(self, width=150, bd=0,)
self.output0.grid(column=0, row=6, columnspan=5, padx=100, pady=0)
self.output1 = tkinter.Entry(self, width=150, bd=0,)
self.output1.grid(column=0, row=7, columnspan=5, padx=100, pady=0)
self.output2 = tkinter.Entry(self, width=150, bd=0,)
self.output2.grid(column=0, row=8, columnspan=5, padx=100, pady=0)
self.output3 = tkinter.Entry(self, width=150, bd=0,)
self.output3.grid(column=0, row=9, columnspan=5, padx=100, pady=0)
self.output4 = tkinter.Entry(self, width=150, bd=0,)
self.output4.grid(column=0, row=10, columnspan=5, padx=100, pady=0)
if __name__ == '__main__':
root = tkinter.Tk()
Adder(root)
root.resizable(width=False, height=False) # locks window from being resized
root.mainloop()
I'm creating a database in python using sqlite3 and tkinter. This is my first time doing something like this so I've been using examples on the internet to help build it. This has worked for the most part, however now I need to be able to display the data in the database in a table, and the example I've used doesn't seem to work properly for me. I've tried looking up other solutions, but nothing seems to help.
The problem is that when I go to open up the table, it doesn't get created. The program simply opens a new window and leaves it at that. There are no errors, so I don't know exactly what's wrong.
This is the entire code I've created so far:
from tkinter import *
import sqlite3
con = sqlite3.connect('test.db')
cur = con.cursor()
class Welcome():
def __init__(self,master):
self.master = master
self.master.geometry('170x110+100+200')
self.master.title('Welcome!')
self.label1=Label(self.master,text='Test Database Main Menu',fg='red').grid(row=0,column=1)
self.button1=Button(self.master,text="Enter Data",fg='green',command=self.gotodataentry).grid(row=1,column=1)
self.button2=Button(self.master,text="Data Records",fg='blue',command=self.gotorecords).grid(row=2,column=1)
self.button3=Button(self.master,text="Exit",fg='red',command=self.exit).grid(row=3,column=1)
def exit(self):
self.master.destroy()
def gotodataentry(self):
root2=Toplevel(self.master)
myGUI=DataEntry(root2)
def gotorecords(self):
root2=Toplevel(self.master)
mygui=Records(root2)
class DataEntry():
def __init__(self,master):
self.master = master
self.master.geometry('250x200+100+200')
self.master.title('Data Entry')
self.label2=Label(self.master,text='Welcome to the data entry menu',fg='red').grid(row=0,column=0)
self.label3=Label(self.master,text='Please enter some text',fg='black').grid(row=3,column=0)
self.label4=Label(self.master,text='Please enter a number',fg='black').grid(row=4,column=0)
self.text1=StringVar()
self.text_entry=Entry(self.master,textvariable=self.text1).grid(row=3,column=1)
self.int1=IntVar()
self.int_entry=Entry(self.master,textvariable=self.int1).grid(row=4,column=1)
self.button4=Button(self.master,text="Save",fg='red',command=lambda: self.savedata(self.text1.get(), self.int1.get())).grid(row=7,column=0)
self.button5=Button(self.master,text="Exit",fg='red',command=self.exit).grid(row=9,column=0)
def exit(self):
self.master.destroy()
def savedata(self, text1, int1):
con = sqlite3.connect('test.db')
cur = con.cursor()
cur.execute('INSERT INTO Data (t1, i1) VALUES (?,?)', (text1, int1))
con.commit()
print('Record inserted in Data')
def Records(self):
def __init__(self, master):
self.master = master
self.master.geometry('250x200+100+200')
self.master.title('Records')
self.connection = sqlite3.connect('test.db')
self.cur = self.connection.cursor()
self.textLabel = Label(self.master, text="Text", width=10)
self.textLabel.grid(row=0, column=0)
self.intLabel = Label(self.master, text="Number", width=10)
self.intLabel.grid(row=0, column=1)
self.showallrecords()
def showallrecords(self):
Data = self.readfromdatabase()
for index, dat in enumerate(Data):
Label(self.master, text=dat[0]).grid(row=index+1, column=0)
Label(self.master, text=dat[1]).grid(row=index+1, column=1)
def readfromdatabase(self):
self.cur.execute("SELECT * FROM Data")
return self.cur.fetchall()
def main():
root=Tk()
myGUIWelcome=Welcome(root)
root.mainloop()
if __name__ == '__main__':
main()
And this is the part I'm struggling with:
def Records(self):
def __init__(self, master):
self.master = master
self.master.geometry('250x200+100+200')
self.master.title('Records')
self.connection = sqlite3.connect('test.db')
self.cur = self.connection.cursor()
self.textLabel = Label(self.master, text="Text", width=10)
self.textLabel.grid(row=0, column=0)
self.intLabel = Label(self.master, text="Number", width=10)
self.intLabel.grid(row=0, column=1)
self.showallrecords()
def showallrecords(self):
Data = self.readfromdatabase()
for index, dat in enumerate(Data):
Label(self.master, text=dat[0]).grid(row=index+1, column=0)
Label(self.master, text=dat[1]).grid(row=index+1, column=1)
def readfromdatabase(self):
self.cur.execute("SELECT * FROM Data")
return self.cur.fetchall()
Could someone please help me figure out what's wrong? Sorry if the solution is incredibly simple, like I said this is my first time doing something like this.
You're right that the solution is incredibly simple :D
Change
def Records(self):
To
class Records:
And the code works perfectly