How to format SQL query output properly in Tkinter? - python

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()

Related

Python tkinter listbox bind on <Button-1> only works on second click

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].

How do I place a tkinter variable in a Pypyodbc server name?

I am pulling a variable from the user when they select one of the radio buttons I provide them. Each radio button variable is set as an actual server I can normally connect to using MsSql.
My below code has a !!!!!!!!!!!!! MY EXAMPLE !!!!!!!!!!!!!!!!!! listed next to the spot I am trying to figure out.
I get a connection error when I use pypyodbc.connect ('Server=serverName;'), but I know it works if I get rid of the radio button variable and enter the actual server name.
Any ideas?
#! /usr/bin/python
import os
import pypyodbc
import tkinter
from tkinter import ttk
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 on_quit(self):
"""Exits program."""
quit()
def calculate(self):
serverName = str(self.selectedTown.get()) #! !!!!!!!!!!!!! MY EXAMPLE !!!!!!!!!!!!!!!!!!
word1 = str(self.workstation1_entry.get())
# num2 = int(self.localid2_entry.get()) # This will be entered in a later statement where user can enter LocationID
# if str(self.selectedTown.get()) in str(self.selectedTown.get()):
connection = pypyodbc.connect('Driver={SQL Server};' #! !!!!!!!!!!!!! MY EXAMPLE !!!!!!!!!!!!!!!!!!
'Server=serverName;'
'Database=mydatabase;'
'Trusted_Connection=yes;')
cursor = connection.cursor()
SQLCommand = ("SELECT Name, Location_ID "
"FROM dbo.PB_Location "
"WHERE Name = ?")
Values = [word1]
cursor.execute(SQLCommand,Values)
results = cursor.fetchone()
if results:
self.answer_label['text'] = str(results[1]) # displays answer
connection.close()
else:
self.answer_label['text'] = "Invalid"
connection.close()
def init_gui(self):
"""Builds GUI."""
self.root.title('ID Lookup')
self.root.option_add('*tearOff', 'FALSE')
self.grid(column=0, row=0, sticky='nsew')
self.menubar = tkinter.Menu(self.root)
self.menu_file = tkinter.Menu(self.menubar)
self.menu_file.add_command(label='Exit', command=self.on_quit)
self.menu_edit = tkinter.Menu(self.menubar)
self.menubar.add_cascade(menu=self.menu_file, label='File')
self.menubar.add_cascade(menu=self.menu_edit, label='Edit')
self.root.config(menu=self.menubar)
self.workstation1_entry = ttk.Entry(self, width=5)
self.workstation1_entry.grid(column=1, row = 2)
self.localid2_entry = ttk.Entry(self, width=5)
self.localid2_entry.grid(column=3, row=2)
self.calc_button = ttk.Button(self, text='Submit',
command=self.calculate)
self.calc_button.grid(column=0, row=3, columnspan=4)
self.answer_frame = ttk.LabelFrame(self, text='Answer',
height=100)
self.answer_frame.grid(column=0, row=4, columnspan=4, sticky='nesw')
self.answer_label = ttk.Label(self.answer_frame, text='')
self.answer_label.grid(column=0, row=0)
self.selectedTown = tkinter.StringVar()
self.selectedTown.set('b1') # make it where the top radio button is selected by default
self.b1 = ttk.Radiobutton(self, text='Texas', value='1srvodbx', variable=self.selectedTown).grid(sticky='W', column=0,row=6, columnspan=1) # sticky W to align everything to left
self.b2 = ttk.Radiobutton(self, text='Oklahoma', value='2srvodbx', variable=self.selectedTown).grid(sticky='W', column=0,row=7, columnspan=1)
self.b3 = ttk.Radiobutton(self, text='Idaho', value='3srvodbx', variable=self.selectedTown).grid(sticky='W', column=0,row=8, columnspan=1)
self.selectedTown.get()
# Labels that remain constant throughout execution.
ttk.Label(self, text='Location ID Finder').grid(column=0, row=0,
columnspan=4)
ttk.Label(self, text='Name').grid(column=0, row=2,
sticky='w')
ttk.Label(self, text='Location ID').grid(column=2, row=2,
sticky='w')
ttk.Separator(self, orient='horizontal').grid(column=0,
row=1, columnspan=4, sticky='ew')
for child in self.winfo_children():
child.grid_configure(padx=5, pady=5)
if __name__ == '__main__':
root = tkinter.Tk()
Adder(root)
root.mainloop()
IIUC the problem is you cannot just plug in a variable name like that. You'll have to do:
connstr = '''Driver={{SQL Server}};Server={};Database=mydatabase;Trusted_Connection=yes;'''.format(serverName)
connection = pypyodbc.connect(connstr)

Access state of object (tkinter, Python3) beginner's level

What I want to get: change of checkbox state changes the state of the Entry widget from 'disabled' into 'normal'. (checkbox off = Entry disabled, checkbox on = Entry normal).
My problem is that I don't know how to access and update the state of entry.
My code:
from tkinter import *
from tkinter import ttk
class App(Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master, padding='20')
self.grid()
self.create_checkbox()
self.create_entry()
def create_checkbox(self):
self.limit = BooleanVar()
Checkbutton(self,
text='Limit length',
variable= self.limit,
command= self.state_update,
).grid(row=1, column=1, sticky=W)
def create_entry(self):
self.entry_low = StringVar()
Entry(self,
width=6,
textvariable=self.entry_low,
state='disabled',
).grid(row=1, column=2, sticky=W)
def state_update(self):
self.entry_low.config(state="normal") #THIS OBVIOUSLY DOES NOT WORK
root = Tk()
root.title("Lottery")
app = App(root)
root.mainloop()
I'm beginner, so I'd be especially grateful for simple solutions.
Save a reference to the entry widget, then call the configure method. To make things easy, give your checkbutton the values for the states. That isn't strictly necessary, you can use a boolean and then translate that to the appropriate state.
def create_checkbox(self):
self.limit = StringVar(value="normal")
checkbutton = Checkbutton(..., onvalue="normal", offvalue="disabled", ...)
checkbutton.grid(...)
def create_entry(self):
self.entry_low = StringVar()
self.entry = Entry(self,
width=6,
textvariable=self.entry_low,
state='disabled',
)
self.entry.grid(row=1, column=2, sticky=W)
def state_update(self):
self.entry.config(state="normal") #THIS OBVIOUSLY DOES NOT WORK
Note: you need to call grid in a second step. grid(...) (as well as place) returns None. If you do x=Entry(...).grid(...), x will always be None.

How can I hide the main tkinter program window whilst logging in using another Toplevel window?

I am practicing with a simple login system. I have a main program window which I wish to hide whilst a login window appears. When the correct password is entered I want the login window to destroy and the main window to reappear (deiconify).
The main program code (LibrarySQL.py):
from tkinter import *
import libraryentrySQL, librarydatabase, login
import sqlite3
import os
def click():
entered_text = entry.get() #collect text from text entry box
output.delete(0.0,END) #clears text box - start clearing from 0.0 (from line 0) to END (after last character)
new_db = sqlite3.connect('dictionary.db')
c=new_db.cursor()
c.execute("SELECT definition FROM Dictionary WHERE word = ?", (entered_text,))
for row in c:
definition = row[0]
break
else:
definition = "No word found in dictionary, try again!"
output.insert(END, definition) #this inserts the contents of variable 'definition' at the beginning (END) - because it was cleared before, END is the at the start
def clickentry(): #this function is run when the 2nd button (entry is pressed)
def definition_submitted(word, definition):
new_db = sqlite3.connect('dictionary.db')
c=new_db.cursor()
c.execute("INSERT INTO Dictionary VALUES (?, ?)", (word, definition))
new_db.commit()
new_db.close()
definition_window = libraryentrySQL.DefinitionWindow(window, definition_submitted) #this creates the object 'definition window' and passes to it 'the window variable'
#so that it can have a canvas
def clickdataview():
new_db = sqlite3.connect('dictionary.db')
c=new_db.cursor()
c.execute("SELECT * FROM Dictionary")
data = c.fetchall()
count = len(data)
database_window = librarydatabase.DatabaseWindow(window, count, data)
new_db.close()
def login_window(window):
log = login.Login(window)
window = Tk()
login_window(window)
window.withdraw()
window.deiconify()
window.title("My Little Dictionary")
#Create the Label
Label(window, text="Enter the word you want defining:").grid(row=0, column=0, sticky=W)
#create entry box
entry=Entry(window, width=20, bg="light green")
entry.grid(row=1, column=0, sticky=W)
#create submit button
Button(window, text="Submit", width=5, command=click).grid(row=2, column=0, sticky=W)
#create second label
Label(window, text="\nDefinition").grid(row=3, column=0, sticky=W)
#create text box
output=Text(window, width=75, height=6, wrap=WORD, background="light green")
output.grid(row=4, column=0, sticky=W)
#create submit button to open enter new definition window
Button(window, text="Enter a New Definition", width=20, command=clickentry).grid(row=5, column=0, sticky=W)
#create open database button to open database view window
Button(window, text="View Dictionary", width=20, command=clickdataview).grid(row=6, column=0, sticky=W)
#Create the Dictionary.db if not already present
if not os.path.isfile("dictionary.db"):
new_db = sqlite3.connect('dictionary.db')
c=new_db.cursor()
c.execute('''CREATE TABLE Dictionary
(word text,
definition text)''')
c.execute('''INSERT INTO Dictionary VALUES
('Algorithm', 'Step by step instructions to complete a task')''')
new_db.commit()
new_db.close()
window.mainloop()
The Login class code (login.py):
from tkinter import *
class Login(Toplevel):
def __init__(self, window):
Toplevel.__init__(self, window)
self.title("Current Library")
Label(self, text="Log in to use this program:").grid(row=0, column=0, sticky=W)
self.userbox=Entry(self, width=20, bg="light green")
self.userbox.grid(row=1, column=0, sticky=W)
self.passbox=Entry(self, width=20, bg="light green")
self.passbox.grid(row=2, column=0, sticky=W)
Button(self, text="Submit", width=5, command=self.clicked).grid(row=3, column=0, sticky=W)
def clicked(self):
username = self.userbox.get()
password = self.passbox.get()
if password == "password":
self.correct = True
self.destroy()
else:
pass
I know exactly where the problem is: the main window hides then reappears instantly due to the order of instructions in the mainloop.
How therefore, can I get the main to hide and the login window to appear UNTIL the password is entered correctly? After which I wish the login window to destroy and the main to reappear?
Any help would be gratefully received.
You can modify the clicked() method of your Toplevel instance to call deiconify, that way it's only called when the Toplevel is destroyed.
class Login(Toplevel):
def __init__(self, window):
Toplevel.__init__(self, window)
# this is the parent/root window
self.window = window
Button(self, text='show main', command=self.click).pack()
def click(self):
self.destroy() # destroy the toplevel
self.window.deiconify() # and restore the root window
And in your main module:
root = Tk()
# make the login instance
Login(root)
# withdraw the main window
root.withdraw()
# set up widgets in main window
...
mainloop()

How can I fetch the result of a SQL Query which uses a variable?

Please help. I am creating a little GUI dictionary and am trying to link the interface to a database. I can enter data (word and definition) into the database correctly but I cannot seem to look up words in the database so that the appropriate definition displays in the output box on my GUI.
Module 1 (main program):
from tkinter import *
import libraryentrySQL
import sqlite3
import os
def click():
entered_text = entry.get() #collect text from text entry box
output.delete(0.0,END) #clears text box - start clearing from 0.0 (from line 0) to END (after last character)
new_db = sqlite3.connect('dictionary.db')
c=new_db.cursor()
try:
definition = c.execute("SELECT definition FROM Dictionary WHERE word=%s", (entered_text))
except:
definition = "No word found in dictionary, try again!"
output.insert(END, definition) #this inserts the contents of variable 'definition' at the beginning (END) - because it was cleared before, END is the at the start
def clickentry(): #this function is run when the 2nd button (entry is pressed)
def definition_submitted(word, definition):
new_db = sqlite3.connect('dictionary.db')
c=new_db.cursor()
c.execute("INSERT INTO Dictionary VALUES (?, ?)", (word, definition))
new_db.commit()
new_db.close()
definition_window = libraryentrySQL.DefinitionWindow(window, definition_submitted) #this creates the object 'definition window' and passes to it 'the window variable'
#so that it can have a canvas
#and also passes the function 'definition_submitted' so that as the new word and definition are entered
#in the this object (second window) it can be passed into the function and the dictionary updated
window = Tk()
window.title("My Little Dictionary")
#Create the Label
Label(window, text="Enter the word you want defining:").grid(row=0, column=0, sticky=W)
#create entry box
entry=Entry(window, width=20, bg="light green")
entry.grid(row=1, column=0, sticky=W)
#create submit button
Button(window, text="Submit", width=5, command=click).grid(row=2, column=0, sticky=W)
#create second label
Label(window, text="\nDefinition").grid(row=3, column=0, sticky=W)
#create text box
output=Text(window, width=75, height=6, wrap=WORD, background="light green")
output.grid(row=4, column=0, sticky=W)
#create submit button to open enter new definition window
Button(window, text="Enter a New Definition", width=20, command=clickentry).grid(row=5, column=0, sticky=W)
#Create the Dictionary.db if not already present
if not os.path.isfile("dictionary.db"):
new_db = sqlite3.connect('dictionary.db')
c=new_db.cursor()
c.execute('''CREATE TABLE Dictionary
(word text,
definition text)''')
c.execute('''INSERT INTO Dictionary VALUES
('Algorithm', 'Step by step instructions to complete a task')''')
new_db.commit()
new_db.close()
window.mainloop()
module 2 (enter word and definition window):
from tkinter import *
class DefinitionWindow(Toplevel):
def __init__(self, root, click_callback):
Toplevel.__init__(self, root)
self.click_callback = click_callback
self.title("Library entry")
#Create the Label
Label(self, text="Enter the word you want to add:").grid(row=0, column=0, sticky=W)
#create entry box
self.word_entry=Entry(self, width=20, bg="light green")
self.word_entry.grid(row=1, column=0, sticky=W)
#create second label
Label(self, text="\nDefinition").grid(row=2, column=0, sticky=W)
#create entry box
self.definition_entry = Entry(self, width=50, bg="light green")
self.definition_entry.grid(row=3, column=0, sticky=W)
#create submit button
Button(self, text="Submit", width=5, command=self.clicked).grid(row=4, column=0, sticky=W)
def clicked(self):
self.click_callback(self.word_entry.get(), self.definition_entry.get()) #when this function is called (on submit button click) it takes the entered
#word and definition and assigns it to click_callback, which is an attribute of DefinitionWindow??
self.destroy() #after the word and definition are added to the call_back variable, the frame containing this instance of definition window is closed
What am I doing wrong? I know it is the "SELECT" SQL command which is not correct. Any help would be gratefully received. Thanks
This is not how SQL queries in Python work.
The execute method returns not a value but a cursor.
When nothing was found, no exception is raised, and the cursor is just empty.
Handling all exceptions blindy in the except block will hide any programming errors.
Furthermore, the parameters marker is not %s but ?.
Finally, a Python tuple with a single value must include a comma to differentiate it from a single expression:
c = new_db.cursor()
c.execute("SELECT definition FROM Dictionary WHERE word = ?", (entered_text,))
for row in c:
definition = row[0]
break
else:
definition = "No word found in dictionary, try again!"
output.insert(END, definition)

Categories

Resources