function call from a function to a function within a class fails - python

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

Related

Running another class in the same window using tkinter

I'm trying to build my first app using python and tkinter.
I'm stuck where I can't run the content from another class into the same first window.
The first window is a login window, here is the full code of the class:
import tkinter as tk
import sqlite3
from tkinter import *
from gamecontent import Gamecontent
class MainApp(Tk):
def __init__(self):
Tk.__init__(self)
self.title('Word Warrior - Sign In')
self.geometry("650x510")
self.resizable(width=False, height=False)
# Create widgets
self.label_username = tk.Label(self, text="Username")
self.label_password = tk.Label(self, text="Password")
self.entry_username = tk.Entry(self)
self.entry_password = tk.Entry(self, show="*")
self.button_login = tk.Button(self, text="Login", command=self.login)
self.button_createacc = tk.Button(self, text="Create Account", command=self.createacc)
# Place widgets
self.label_username.place(x=200, y=150)
self.label_password.place(x=200, y=200)
self.entry_username.place(x=280, y=152, width=140, height=27)
self.entry_password.place(x=280, y=202, width=140, height=27)
self.button_login.place(x=280, y=242, width=140, height=27)
self.button_createacc.place(x=280, y=282, width=140, height=27)
# Create database and tables and cursor object
self.conn = sqlite3.connect('users.db')
self.c = self.conn.cursor()
self.c.execute("CREATE TABLE IF NOT EXISTS users (username text UNIQUE, password text)")
self.conn.commit()
self.conn.close()
def clear_content(self):
for widget in self.winfo_children():
widget.destroy()
def login(self):
# Get the username and password from the entry widgets
username = self.entry_username.get()
password = self.entry_password.get()
# Fetch username and password from the database
conn = sqlite3.connect('users.db')
c = conn.cursor()
c.execute("SELECT * FROM users WHERE username=? AND password=?", (username, password))
result = c.fetchone()
conn.close()
# Check if the username and password are correct
if result:
# If the login is successful, open a new window with the flashcard game
self.clear_content()
Gamecontent()
else:
# If the login is not successful, display an error message
self.label_message = tk.Label(self, text=" Wrong credentials ")
self.label_message.place(x=285, y=322)
def createacc(self):
# Get the username and password from the entry widgets
username = self.entry_username.get()
password = self.entry_password.get()
# Checks if user is entering an empty username/password while creating
if username == "" or password == "":
self.label_message = tk.Label(self, text=" Can't be empty ")
self.label_message.place(x=290, y=322)
else:
# Connect to the database (or create it if it doesn't exist)
conn = sqlite3.connect('users.db')
c = conn.cursor()
# Create the table if it doesn't exist
c.execute('''CREATE TABLE IF NOT EXISTS users
(username text, password text)''')
# Checks if an account with the same username exists
c.execute("SELECT * FROM users WHERE username = ?", (username,))
if c.fetchone() is None:
c.execute("INSERT INTO users VALUES (?, ?)", (username, password))
conn.commit()
self.label_message = tk.Label(self, text=" Account created ")
self.label_message.place(x=290, y=322)
else:
self.label_message = tk.Label(self, text=" Username exists ")
self.label_message.place(x=290, y=322)
# Close the connection
conn.close()
app = MainApp()
app.mainloop()
The change must be done when the login is correct, exactly in
self.clear_content()
Gamecontent()
The problem is that Gamecontent opens in another window and not into the same window.
Here is the code for Gamecontent class
from tkinter import *
from random import randint
from gamedata import words, count
class Gamecontent(Tk):
def __init__(self):
Tk.__init__(self)
self.title('Word Warrior - Play')
self.geometry("650x510")
self.resizable(width=False, height=False)
def next():
global hinter, hinter_count
# Clear the screen
answer_label.config(text="")
my_entry.delete(0, END)
hint_label.config(text="")
# Reset Hint stuff
hinter = ""
hinter_count = 0
# Create random selection
global random_word
random_word = randint(0, count-1)
# update label with Spanish Word
spanish_word.config(text=words[random_word][0])
def answer():
if my_entry.get().capitalize() == words[random_word][1]:
answer_label.config(text=f"Correct! {words[random_word][0]} is {words[random_word][1]}")
else:
answer_label.config(text=f"Incorrect! {words[random_word][0]} is not {my_entry.get().capitalize()}")
def hint():
global hinter_count
global hinter
if hinter_count < len(words[random_word][1]):
hinter = hinter + words[random_word][1][hinter_count]
hint_label.config(text=hinter)
hinter_count +=1
# Labels
spanish_word = Label(self, text="", font=("Helvetica", 36))
spanish_word.pack(pady=50)
answer_label = Label(self, text="")
answer_label.pack(pady=20)
my_entry = Entry(self, font=("Helvetica", 18))
my_entry.pack(pady=20)
# Create Buttons
button_frame = Frame(self)
button_frame.pack(pady=20)
answer_button = Button(button_frame, text="Answer", command=answer)
answer_button.grid(row=0, column=0, padx=20)
next_button = Button(button_frame, text="Next", command=next)
next_button.grid(row=0, column=1)
hint_button = Button(button_frame, text="Hint", command=hint)
hint_button.grid(row=0, column=2, padx=20)
# Create Hint Label
hint_label = Label(self, text="")
hint_label.pack(pady=15)
# Run next function when program starts
next()
self.mainloop()
I'm stuck with this for a while and can't move forward, I'm not even sure it's possible with tkinter to do so.
I tried clearing the content of the window and start an instance of the second class but it opens in another window.
Change
self.clear_content()
Gamecontent()
to
self.clear_content()
Gamecontent(self)
In gamecontent itself change
class Gamecontent(Tk):
def __init__(self):
Tk.__init__(self)
self.title('Word Warrior - Play')
self.geometry("650x510")
self.resizable(width=False, height=False)
to
class Gamecontent(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
#self.config(bg="white")
self.pack(fill=BOTH, expand=True)
parent.title('Word Warrior - Play')
This makes gamecontent to a frame which packs itself into your main app

How to delete only one row in tkinter python?

when i run app and delete one row is worked but whene i close the app to update, all rows are deleted
what should i do
import sqlite3
from tkinter import *
from tkinter import ttk
class root(Tk):
def __init__(self):
super().__init__()
self.bookInfodb = sqlite3.connect("test.db")
self.c = self.bookInfodb.cursor()
self.bookInfodb.commit()
self.c.execute(
"CREATE TABLE IF NOT EXISTS books (title TEXT, author TEXT, year TEXT, isbn TEXT)")
self.title("book info")
self.minsize(500, 400)
self.configure(background="gray")
self.datas()
self.fetch()
def fetch(self):
self.c.execute("SELECT * FROM books")
rows = self.c.fetchall()
for row in rows:
self.list_box.insert(END, row)
def delete_item(self):
selected_item = self.list_box.curselection()
for item in selected_item:
self.list_box.delete(item)
self.c.execute("DELETE FROM books")
self.bookInfodb.commit()
def addData(self, title, years, author, isbn):
self.c.execute(
"INSERT INTO books VALUES (?,?,?,?)", (
self.title.get(),
self.years.get(),
self.author.get(),
self.isbn.get()))
self.bookInfodb.commit()
def datas(self):
self.title = StringVar()
self.titleEntry = ttk.Label(self, text="titel")
self.titleEntry.place(x=41, y=10)
entry = Entry(self, textvariable=self.title)
entry.place(x=66, y=10)
# make years input
self.years = StringVar()
self.yearsEntry = ttk.Label(self, text="years")
self.yearsEntry.place(x=269, y=10)
entry2 = Entry(self, textvariable=self.years)
entry2.place(x=300.5, y=10.2)
# make author input
self.author = StringVar()
self.authorEntry = ttk.Label(self, text="author")
self.authorEntry.place(x=40, y=51)
entry3 = Entry(self, textvariable=self.author)
entry3.place(x=80, y=51)
# make isbn input
self.isbn = StringVar()
self.isbnEntry = ttk.Label(self, text="isbn")
self.isbnEntry.place(x=270, y=52)
entry_iv = Entry(self, textvariable=self.isbn)
entry_iv.place(x=297, y=52)
# listbox
self.list_box = Listbox(self, height=10, width=50)
self.list_box.place(x=85, y=200)
# buttons
save_button = Button(
self,
text=" save ",
command=(
lambda t=self.title.get(), y=self.years.get(), a=self.author.get(), i=self.isbn: self.addData(t, y, a, i)),)
save_button.place(x=66, y=150)
delete_button = Button(self, text="delete", command=self.delete_item)
delete_button.place(x=215, y=150)
windows = root()
windows.mainloop()
I don't know if this is the problem but self.c.execute("DELETE FROM books") will delete the entire books table.
You probably need to add a WHERE clause in your DELETE statement
self.c.execute("DELETE FROM books WHERE ...")

How to fetch one row and display it on textbox and increment it automatically

i wrote this python 3 program, i want to for each row in field Esperanto, get it's corresponding row in the other field in database named English. for example: when i click on row 1 in listbox, i want the text of the row 1 in English field of my db to be displayed on the textbox. now it fetches all the rows and it's a disaster, how can i do that? thanks.
#! /usr/bin/env python3
#GeologyDict by Ali M
import sqlite3 as sqlite
import tkinter as tk
from tkinter import Text
from tkinter import Entry
from tkinter import Scrollbar
from tkinter import ttk
#GUI Widgets
class EsperantoDict:
def __init__(self, master):
master.title("EsperantoDict")
master.resizable(False, False)
master.configure(background='#EAFFCD')
self.style = ttk.Style()
self.style.configure("TFrame", background='#EAFFCD')
self.style.configure("TButton", background='#EAFFCD')
self.style.configure("TLabel", background='#EAFFCD')
self.frame_header = ttk.Frame(master, relief=tk.FLAT)
self.frame_header.pack(side=tk.TOP, padx=5, pady=5)
self.logo = tk.PhotoImage(file=r'C:\EsperantoDict\eo.png')
self.small_logo = self.logo.subsample(10, 10)
ttk.Label(self.frame_header, image=self.small_logo).grid(row=0, column=0, stick="ne", padx=5, pady=5, rowspan=2)
ttk.Label(self.frame_header, text='EsperantoDict', font=('Arial', 18, 'bold')).grid(row=0, column=1)
self.frame_content = ttk.Frame(master)
self.frame_content.pack()
self.entry_search = ttk.Entry(self.frame_content)
self.entry_search.grid(row=0, column=0)
self.entry_search.insert(tk.END, "Type to Search")
self.entry_search.bind('<Button-1>', self.entry_delete)
self.button_search = ttk.Button(self.frame_content, text="Search")
self.aks = tk.PhotoImage(file=r'C:\EsperantoDict\search.png')
self.small_aks = self.aks.subsample(3, 3)
self.button_search.config(image=self.small_aks, compound=tk.LEFT)
self.button_search.grid(row=0, column=1, columnspan=2)
self.listbox = tk.Listbox(self.frame_content, height=28)
self.listbox.grid(row=1, column=0)
self.scrollbar = ttk.Scrollbar(self.frame_content, orient=tk.VERTICAL, command=self.listbox.yview)
self.scrollbar.grid(row=1, column=1, sticky='ns')
self.listbox.config(yscrollcommand=self.scrollbar.set)
self.listbox.bind('<<ListboxSelect>>', self.enter_meaning)
self.textbox = tk.Text(self.frame_content, width=60, height=27)
self.textbox.grid(row=1, column=2)
# SQLite
self.db = sqlite.connect(r'C:\EsperantoDict\test.db')
self.cur = self.db.cursor()
self.cur.execute('SELECT Esperanto FROM Words')
for row in self.cur:
self.listbox.insert(tk.END, row)
# SQLite
def enter_meaning(self, tag):
if self.listbox.curselection():
results = self.cur.execute("SELECT English FROM Words")
for row in results:
self.textbox.insert(tk.END, row)
def entry_delete(self, tag):
self.entry_search.delete(0, tk.END)
return None
def main():
root = tk.Tk()
esperantodict = EsperantoDict(root)
root.mainloop()
if __name__ == '__main__': main()
#db table name: Words
##db first field name: Esperanto
##db second field name: English

Multiple GUI with Tkinter

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 *

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)

Categories

Resources