name 'connection' is not defined - python

I'm trying to close the ODBC connection and I'm not sure about the best way to implement this.
My program runs but I'm wanting to close the connection properly with connection.close(). Here is my original:
import pypyodbc
def queryfirst():
return ("SELECT FIRSTNAME, LASTNAME "
"FROM dbo.MAIN "
"WHERE FIRSTNAME = ?")
def sqlfirst():
firstname = "Josh"
if True:
connection = pypyodbc.connect('Driver={SQL Server};Server=;Database=;Trusted_Connection=yes;')
cursor = connection.cursor()
SQLCommand = queryfirst()
Values = [firstname]
cursor.execute(SQLCommand,Values)
return cursor.fetchmany(2)
def calculate():
results = sqlfirst()
if results:
print (results[0]) # prints the first and last name
calculate()
I've tried this:
import pypyodbc
def queryfirst():
return ("SELECT FIRSTNAME, LASTNAME "
"FROM dbo.V_LICMAIN_IT "
"WHERE FIRSTNAME = ?")
def sqlfirst(closeit):
firstname = "Josh"
if True:
connection = pypyodbc.connect('Driver={SQL Server};Server=;Database=;Trusted_Connection=yes;')
cursor = connection.cursor()
SQLCommand = queryfirst()
Values = [firstname]
cursor.execute(SQLCommand,Values)
return cursor.fetchmany(1)
connection.close() = closeit
def calculate():
results = sqlfirst()
if results:
print (results[0]) # prints the first and last name
sqlfirst(closeit)
calculate()
The above says:
connection.close() = closeit
SyntaxError: can't assign to function call
And this with no luck:
import pypyodbc
def queryfirst():
return ("SELECT FIRSTNAME, LASTNAME "
"FROM dbo.MAIN "
"WHERE FIRSTNAME = ?")
def closeconn():
return connection.close()
def sqlfirst():
firstname = "Josh"
if True:
connection = pypyodbc.connect('Driver={SQL Server};Server=;Database=;Trusted_Connection=yes;')
cursor = connection.cursor()
SQLCommand = queryfirst()
Values = [firstname]
cursor.execute(SQLCommand,Values)
return cursor.fetchmany(2)
testname = closeconn()
def calculate():
results = sqlfirst()
if results:
print (results[0]) # prints the first and last name
closeconn()
calculate()
The above says:
return connection.close()
NameError: name 'connection' is not defined
UPDATE: Below is my full code:
import os
import pypyodbc
import tkinter
from tkinter import ttk
from tkinter import messagebox
from tkinter import BOTH, END, LEFT
import traceback
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 queryfirst(self):
return ("SELECT LASTNAME, FIRSTNAME, ID "
"FROM dbo.TABLENAME " # table name
"WHERE FIRSTNAME = ?")
def connect(self):
return pypyodbc.connect('Driver={SQL Server};Server=;Database=;Trusted_Connection=yes;')
def sqlfirst(self):
firstname = str(self.first_entry.get())
lastname = str(self.last_entry.get())
license = str(self.lic_entry.get())
if (firstname and not lastname and not license): # "You entered first name."
try:
connection = self.connect()
except pypyodbc.Error as ex:
sqlstate = ex.args[0]
if sqlstate == '28000':
self.output0.delete(0, END)
self.output0.insert(0,"You do not have access.")
cursor = connection.cursor()
SQLCommand = self.queryfirst()
Values = [firstname]
cursor.execute(SQLCommand,Values)
return cursor.fetchmany(10)
# connection.close() # !!!!!! <<< this is what I'm working on
def calculate2(self):
results = self.sqlfirst()
if results:
self.output2.delete(0, END)
self.output2.insert(0,results[2])
def calculate1(self):
results = self.sqlfirst()
if results:
self.output1.delete(0, END)
self.output1.insert(0,results[1])
def calculate(self):
results = self.sqlfirst()
if results:
self.output0.delete(0, END)
self.output0.insert(0,results[0])
self.calculate1()
self.calculate2()
def init_gui(self):
"""Builds GUI."""
self.root.title('Verify')
self.root.option_add('*tearOff', 'FALSE')
# 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.output0 = tkinter.Entry(self, width=150, bd=0,)
self.output0.grid(column=0, row=6, columnspan=5, padx=10)
self.output0.bind("<Key>", lambda e: "break")
self.output1 = tkinter.Entry(self, width=150, bd=0,)
self.output1.grid(column=0, row=7, columnspan=5, padx=10)
self.output1.bind("<Key>", lambda e: "break")
self.output2 = tkinter.Entry(self, width=150, bd=0,)
self.output2.grid(column=0, row=8, columnspan=5, padx=10)
self.output2.bind("<Key>", lambda e: "break")
self.blank.grid(row=16,)
if __name__ == '__main__':
root = tkinter.Tk()
Adder(root)
root.resizable(width=False, height=False) # locks window from being resized
root.mainloop()

Looks like you got an exception and masked it because sqlstate was not '28000'.
try:
connection = self.connect()
except pypyodbc.Error as ex:
sqlstate = ex.args[0]
if sqlstate == '28000':
self.output0.delete(0, END)
self.output0.insert(0,"You do not have access.")
else:
self.output0.insert(0,"Some other database error ({})".format(
ex.message
))
else:
cursor = connection.cursor()
SQLCommand = self.queryfirst()
Values = [firstname]
cursor.execute(SQLCommand,Values)
try:
return cursor.fetchmany(10)
finally:
connection.close()
Also note that any line after a return statement will not be executed unless it is inside a finally block.

Related

Label not changing in window - tkinter

I have this code that I'm following from a video. This is a function that gets activated when a button is pressed. In some parts I want to erase the previous output in a label every time the button is pressed:
# Search customers
def search_customers():
search_customers = Tk()
search_customers.title("Search Customers")
search_customers.geometry("1300x600")
searched_label = Label(search_customers)
searched_label.grid(row=2, column=0)
test = Label(search_customers)
test.grid(row=3, column=0)
def search_now():
# searched_label = Label(search_customers)
# searched_label.grid(row=2, column=0)
selected = drop.get() # This is a Combobox
if selected == 'Search By...':
sql = ""
test['text'] = 'You forgot to pick an option'
elif selected == 'Last Name':
sql = "SELECT * FROM customers WHERE last_name = %s"
elif selected == 'Email Address':
sql = "SELECT * FROM customers WHERE email = %s"
elif selected == 'Customer ID':
sql = "SELECT * FROM customers WHERE user_id = %s"
searched = search_box.get()
name = (searched, )
result = my_cursor.execute(sql, name)
if selected == "Search By...":
result = ''
else:
result = my_cursor.fetchall()
if not result:
result = "Record Not Found"
test['text'] = ''
searched_label['text'] = result
elif result:
test['text'] = ''
searched_label['text] = ''
searched_label = Label(search_customers)
for index, x in enumerate(result):
num = 0
index += 2
for y in x:
searched_label = Label(search_customers, text=y)
searched_label.grid(row=index, column=num)
num += 1
The thing is, every time the code reaches this statement: searched_label['text'] = '', it says: variable referenced before the assignment but that doesn't happen with test['text'] = '' even though both labels are created in the same scope.
The only way it worked was to create searched_label inside the search_now() (see the commented lines and let's pretend to uncomment them and comment the ones above).
With the lines uncommented inside search_now(), when it reaches this statement: if not result, it sets searched_label['text'] = result without a problem, but when it reaches the last elif, it doesn't set searched_label['text'] = '', actually, let's say the code was run and it first reached the if not result: statement so when the button is press again and it reaches the last elif it doesn't erase the previous output with searched_label['text] = ''.
In this last elif, I tried reached_label.grid_remove() and creating the label again but the previous output still remains so it mixes with the new output.
Thanks in advance, I'm still learning and I hope my question is clear enough
If you want to change the texts of Label widgets regularily, it pays to use the parameter textvariable. It takes a StringVar() object that can be changed by any function. As soon as the StringVar gets a new value, the label changes.
I do not see the whole of your program, but this is how it works in general:
def search_customers():
search_customers = Tk()
search_customers.title("Search Customers")
search_customers.geometry("1300x600")
global labeltext
labeltext = StringVar() ## Initiate a string variable
labeltext.set("This is the mutable text")
searched_label = Label(search_customers,textvariable=labeltext)
searched_label.grid(row=2, column=0)
test = Button(search_customers,text="Change it",command=change)
test.grid(row=3, column=0)
def change():
labeltext.set("This is a new text")
If the program gets more complicated, you might also consider defining the dialog box as a new class, iheriting from Frame. There, you can define methods that have access to all widgets and variables without the need of global variables.
I can't help you. Actually, need more information. I am using match case statements instead of if/else.
Code:
def search_now():
searched_label = Label(search_customers)
searched_label.grid(row=2, column=0)
selected = drop.get() # This is a Combobox
match selected:
case 'Search By...':
sql = ""
test['text'] = 'You forgot to pick an option'
case 'Last Name':
sql = "SELECT * FROM customers WHERE last_name = %s"
case 'Email Address':
sql = "SELECT * FROM customers WHERE email = %s"
case 'Customer ID':
sql = "SELECT * FROM customers WHERE user_id = %s"
searched = search_box.get()
name = (searched, )
result = my_cursor.execute(sql, name)
if selected == "Search By...":
result = ''
else:
result = my_cursor.fetchall()
if not result:
result = "Record Not Found"
#test['text'] = ''
searched_label.config{text=result)
elif result:
#test['text'] = ''
searched_label.config(text='')
#searched_label = Label(text=search_customers)
for index, x in enumerate(result):
num = 0
index += 2
for y in x:
#searched_label = Label(search_customers, text=y)
searched_label.config(text=y)
Let me know if this work.

MySql Class Object function error - python

I am subscribing to a data stream using a class object to insert the data into a databse using MySql. Could anyone shed some light on where my error is coming from?
traceback error:
File "/media/.........../stream.py", line 51, in database_insert
self.cursor.execute(self.insert, self.values)
AttributeError: 'NoneType' object has no attribute 'execute'
*** I have the while loop commented out because its easier. Instead, I am using an example json string in its place until my script is ready to be ran.
import asyncio
from binance import AsyncClient, BinanceSocketManager
import mysql.connector
from mysql.connector import errorcode
import datetime
import json
class Stream:
def __init__(self):
self.cnx = None
self.cursor = None
def database_connect(self):
self.cnx = mysql.connector.connect(user='root',
password='',
host='localhost',
database='')
self.cursor = self.cnx.cursor()
return self.cursor
def database_disconnect(self):
self.cnx = mysql.connector.connect(user='root',
password='',
host='localhost',
database='')
self.close = self.cnx.close()
def accounting_insert(self, query, data_tuple):
self.cursor.execute(query, data_tuple)
self.cnx.commit()
self.cnx.close()
print('Data has been successfully inserted into the database.')
def database_insert(self, ticker, timestamp, price):
self.insert = ("INSERT INTO data_" + ticker + " "
"(timestamp, price) "
"VALUES (%s, %s)")
self.values = (int(timestamp), float(price))
self.cursor.execute(self.insert, self.values)
self.cnx.commit()
self.cnx.close()
print("Values Inserted.")
def ticker(self, res):
longTicker = res['data']['s']
if longTicker == 'BTCUSDT':
return 'BTC'
elif longTicker == 'BCHUSDT':
return 'BCH'
def timestamp(self, res):
return res['data']['E']
def price(self, res):
return res['data']['p']
try:
Stream().database_connect()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
print("success")
async def main():
client = await AsyncClient.create()
bm = BinanceSocketManager(client)
# pass a list of stream names
ms = bm.multiplex_socket(['btcusdt#trade', 'bchusdt#trade'])
# then start receiving messages
async with ms as tscm:
#while True:
#res = await tscm.recv()
#print(res)
res = {'stream': 'btcusdt#trade', 'data': {'e': 'trade', 'E': 1620716700815, 's': 'BTCUSDT', 't': 272261278, 'p': '65551.60000000', 'q': '25.76580000', 'b': 2142679715, 'a': 2142679312, 'T': 1620716700814, 'm': False, 'M': True}}
ticker = Stream().ticker(res)
timestamp = Stream().timestamp(res)
price = Stream().price(res)
print("Ticker: " + str(ticker) + " " + "Time: " + str(timestamp) + " " + "Price: $" + str(price))
Stream().database_insert(ticker, timestamp, price)
await client.close_connection()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Stream().database_disconnect()
When you do Stream(), you are creating an instance of Stream with its own set of values for cnx and cursor. You have created Stream instances at multiple places and expected them to point to a single instance which isn't the case.
In the below snippet
s1 = Stream()
s2 = Stream()
s1 and s2 point to different instances of Stream. So, the cnx and cur of s1 will be different from that of s2.
You have to do the below changes to make your code work.
try:
stream = Stream().database_connect()
except mysql.connector.Error as err:
.....
.....
else:
print("success")
async def main():
client = await AsyncClient.create()
....
....
async with ms as tscm:
....
....
ticker = stream.ticker(res)
timestamp = stream.timestamp(res)
price = stream.price(res)
print("Ticker: " + str(ticker) + " " + "Time: " + str(timestamp) + " " + "Price: $" + str(price))
stream.database_insert(ticker, timestamp, price)
stream.database_disconnect()
await client.close_connection()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

How to increment the number in results[0]?

I have a Python/Tkinter program and I am trying to increment some numbers that are at the end of a variable used for tk.Entry boxes.
For example, self.output0, self.output1, self.output2, etc
(Sorry, my code is long so I tried shortening it up for an example.)
self.entries = []
self.output0 = tk.Entry(self, width=149, justify='center', bd='0', bg='#E0E0E0')
self.output0.grid(column=0, row=6, columnspan=5, padx=1)
self.output1 = tk.Entry(self, width=149, justify='center', bd='0', bg='#E0E0E0')
self.output1.grid(column=0, row=7, columnspan=5, padx=1)
I grab the users input with another entry box such as 'self.first_entry' and run a SQL query on the user input.
For example:
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 authenticate(self):
return pypyodbc.connect('Driver={SQL Server};Server=MYSERVERNAME;Database=MYDATABASENAME;Trusted_Connection=yes;')
def calculate(self):
firstname = str(self.first_entry.get()) # converts user entry into variable
lastname = str(self.last_entry.get())
license = str(self.lic_entry.get())
try:
connection = self.authenticate()
except pypyodbc.Error as ex:
sqlstate = ex.args[0]
if sqlstate == '28000':
self.output0.delete(0, END)
self.output0.insert(0,"You do not have access.")
cursor = connection.cursor()
if (firstname and not lastname and not license): # "You entered first name."
SQLCommand = ("SELECT LASTNAME, FIRSTNAME, LICNUMBER "
"FROM MyTABLEName " # table name
"with (nolock)"
"WHERE FIRSTNAME LIKE ?")
Values = [firstname + '%']
else:
SQLCommand = ("SELECT LASTNAME, FIRSTNAME, LICNUMBER "
"FROM MyTABLEName " # table name
"(nolock)"
"WHERE FIRSTNAME LIKE ? AND LASTNAME LIKE ? AND LICNUMBER LIKE ?")
Values = [firstname + '%', lastname + '%', '%' + license + '%']
cursor.execute(SQLCommand,Values)
results = cursor.fetchmany(10)
if results:
self.output0.delete(0, END) # clears entry
self.output0.insert(0,results[0]) # enters results in entry
self.output1.delete(0, END) # clears entry
self.output1.insert(0,results[1]) # enters results in entry
self.output2.delete(0, END) # clears entry
self.output2.insert(0,results[2]) # enters results in entry
self.output3.delete(0, END) # clears entry
self.output3.insert(0,results[3]) # enters results in entry
self.output4.delete(0, END) # clears entry
self.output4.insert(0,results[4]) # enters results in entry
connection.close()
else:
self.output0.delete(0, END)
self.output0.insert(0,"There are no records for this input.")
The above will output 5 rows from the database.
I am wanting to shorten the code up. How can I take the below and write it so that I do not have to repeat
self.output0.delete(0, END) # clears entry
self.output0.insert(0,results[0]) # enters results in entry
self.output1.delete(0, END) # clears entry
self.output1.insert(0,results[1]) # enters results in entry
2
2
3
3
...etc
I want to increment the outputX and the number in results[x]
This below is what I have been trying but it is not working:
cursor.execute(SQLCommand,Values)
results = cursor.fetchmany(10)
self.outputs = [self.output0, self.output1, self.output2, self.output3, self.output4]
for output in self.outputs:
for i in range(0, 4):
if results:
output.delete(0, END) # clears entry
output.insert(0,results[i]) # enters results in entry
else:
self.output0.delete(0, END)
self.output0.insert(0,"There are no records for this input.")
How can I increment the number in "resuls[x]" so that I get a different row from the SQL query? It keeps printing the same row on each line.
The problem is that you're trying to index your cursor. Try converting it to a list first and then running the function.
results = list(cursor.fetchmany(10))
One easy and not so intrusive solution would be to use getattr:
def update_fields(self, prefix, values):
for x, _ in enumerate(values):
attr = getattr(self, prefix + str(x))
attr.delete(0, END)
attr.insert(0, values[x])
And then you'd just:
results = cursor.fetchmany(10)
if results:
self.update_fields('output', results)
Please note that getattr will raise an AttributeError if self has no declared field named outputX
You can ignore undeclared fields by swallowing the exception:
def update_fields(self, prefix, values):
for x, _ in enumerate(values):
try:
attr = getattr(self, prefix + str(x))
attr.delete(0, END)
attr.insert(0, values[x])
except AttributeError:
pass
# You can also use continue

How python pymysql.cursors get INOUT return result from mysql stored procedure

I have mysql proc:
CREATE DEFINER=`user`#`localhost` PROCEDURE `mysproc`(INOUT par_a INT(10), IN par_b VARCHAR(255) , IN par_c VARCHAR(255), IN par_etc VARCHAR(255))
BEGIN
// bla... insert query here
SET par_a = LAST_INSERT_ID();
END$$
DELIMITER ;
to test that sp, if i run:
SET #par_a = -1;
SET #par_b = 'one';
SET #par_c = 'two';
SET #par_etc = 'three';
CALL mysproc(#par_a, #par_b, #par_c, #par_etc);
SELECT #par_a;
COMMIT;
it return #par_a as what i want - so i assume my db is fine...
then...
I have python as follow:
import pymysql.cursors
def someFunction(self, args):
# generate Query
query = "SET #par_a = %s; \
CALL mysproc(#par_a, %s, %s, %s); \
SELECT #par_a \
commit;"
try:
with self.connection.cursor() as cursor:
cursor.execute(query,(str(par_a), str(par_b), str(par_c), str(par_etc)))
self.connection.commit()
result = cursor.fetchone()
print(result) # <-- it print me 'none' how do i get my #par_a result from mysproc above?
return result
except:
raise
finally:
self.DestroyConnection()
result: the stored proc executed, as i can see record in.
problem: but i cant get my #par_a result in my python code from mysproc above?
and, if i change:
# generate Query
query = "SET #par_a = '" + str(-1) + "'; \
CALL mysproc(#par_a, %s, %s, %s); \
SELECT #par_a \
commit;"
to
# generate Query
query = "SELECT 'test' \
commit;"
and
cursor.execute(query)
strangely, it give me the correct result ('test',)
I used this class and I got response.
import pymysql.cursors
class connMySql:
def __init__(self, User, Pass, DB, Host='localhost', connShowErr=False, connAutoClose=True):
self.ShowErr = connShowErr
self.AutoClose = connAutoClose
self.DBName = DB
try:
self.connection = pymysql.connect(host=Host,
user=User,
password=Pass,
db=DB, #charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
except ValueError as ValErr:
if self.ShowErr == True: print(ValErr)
return False
def Fetch(self, Query):
try:
with self.connection.cursor() as cursor:
# Read a single record
cursor.execute(Query)
result = cursor.fetchall()
return result
except ValueError as ValErr:
if self.ShowErr == True: print(ValErr)
return False
finally:
if self.AutoClose == True: self.connection.close()
def Insert(self, Query):
try:
with self.connection.cursor() as cursor:
# Create a new record
cursor.execute(Query)
# connection is not autocommit by default. So you must commit to save
# your changes.
self.connection.commit()
except ValueError as ValErr:
if self.ShowErr == True: print(ValErr)
return False
finally:
if self.AutoClose == True: self.connection.close()
def ProcedureExist(self, ProcedureName):
try:
result = self.Fetch("SELECT * FROM mysql.proc WHERE db = \"" + str(self.DBName) + "\";")
Result = []
for item in result:
Result.append(item['name'])
if ProcedureName in Result:
return True
else:
return False
except ValueError as ValErr:
if self.ShowErr == True: print(ValErr)
return False
def CallProcedure(ProcedureName, Arguments=""):
try:
# Set arguments as a string value
result = self.Fetch('CALL ' + ProcedureName + '(' + Arguments + ')')
except ValueError as ValErr:
if self.ShowErr == True: print(ValErr)
return False
finally:
if self.AutoClose == True: self.connection.close()
def CloseConnection(self):
try:
self.connection.close()
return True
except ValueError as ValErr:
if self.ShowErr == True: print(ValErr)
return False
def main():
objMysqlConn = connMySql('user', '1234', 'myDB', connShowErr=True, connAutoClose=False)
ProcedureName= "mysproc"
if objMysqlConn.ProcedureExist(ProcedureName):
result = objMysqlConn.Fetch('CALL ' + ProcedureName + '()')
if result != False:
result = result[0]
print(result)
else:
print("The procecure does not exist!")
if __name__ == '__main__':
main()

Bug in message sending program

I am just experimenting on a messaging program which runs on one computer only. Okay, here's the problem: If I login as an user and send a message to another user, even when I login to the message receiving user, no messages are not there(it say no messages). Please help me out. You are also welcome to give your own suggestions and ways to simplify the code.
import Tkinter as tk
import sys
import tkMessageBox
import csv
accounts = dict()
messages = []
messagerec = []
messagesen = []
csvpath = "C:/Users/user1/Desktop/abc.csv"
csvreader = csv.reader(open(csvpath))
for y, z in csvreader:
accounts[y] = z
def GetUser():
user = userid.get()
return user
def GetPass():
password = passid.get()
return password
def SignUp():
def signupgo():
newuser = newuserid.get()
newpass = newpassid.get()
if newuser in accounts:
tkMessageBox.showerror("Username Taken", 'Sorry! The username you have requested has already been taken. Please try another username.' [2])
else:
accounts[newuser] = newpass
tkMessageBox.showinfo("Account Created", 'Congratulations! Your account has been created' [2])
newuserid = tk.StringVar()
newpassid = tk.StringVar()
SignUpWin = tk.Tk()
NewUserLabel = tk.Label(SignUpWin, text="New Username: ").pack()
NewUserInput = tk.Entry(SignUpWin,textvariable=newuserid).pack()
NewPassLabel = tk.Label(SignUpWin, text="New Password: ").pack()
NewPassInput = tk.Entry(SignUpWin, textvariable=newpassid).pack()
CreateAccount = tk.Button(SignUpWin, text="Create Account", command=signupgo).pack()
def logingo():
user = GetUser()
password = GetPass()
if user in accounts:
if accounts[user] == password:
LoggedIn(user)
elif accounts[user] != password:
tkMessageBox.showerror("Wrong Password", 'Try Again! You have entered the wrong password.')
elif user not in accounts:
tkMessageBox.showerror("User not existing", 'Try Again or Create an account! The username you have provided is not existing.')
def LoggedIn(user):
def MessageButtonClick():
if tkMessageBox.askquestion('Compose or Inbox?', 'Do you want to access your inbox(Yes) or compose a new message(No)?') == 'yes':
OpenInbox(user)
else:
MessageSender(user)
The message sending part starts here.
def MessageSender(user):
messagerecvar = tk.StringVar()
messagecontentvar = tk.StringVar()
messagesenderwin = tk.Tk()
messagereclabel = tk.Label(messagesenderwin, text="Receiver:").pack()
messagerecinput = tk.Entry(messagesenderwin, textvariable=messagerecvar).pack()
messagecontentlabel = tk.Label(messagesenderwin, text="Content:").pack()
messagecontentinput = tk.Entry(messagesenderwin, textvariable=messagecontentvar).pack()
messagecontent = messagecontentvar.get()
messagerec = messagerecvar.get()
messagesendgobutton = tk.Button(messagesenderwin, text='Send Message', command=lambda:sendmessagego(messagecontent, user, messagerec)).pack()
def sendmessagego(content, sender, receiver):
messages.append(content)
messageno = len(messages)
messagerec.append(receiver)
messagesen.append(sender)
tkMessageBox.showinfo("Message Sent", 'Your message has been sent.')
def OpenInbox(user):
if 'a' in messagerec:
lenmess = messagerec.index(user)
tkMessageBox.showinfo('Message from '+messagesen[lenmess], 'Message from '+messagesen[lenmess]+': '+messages[lenmess])
elif user not in messagerec:
tkMessageBox.showinfo('No Messages', 'Sorry, no messages were found')
loggedinwin = tk.Tk()
tkMessageBox.showinfo("Welcome", 'Hello, '+user)
HomeLabel = tk.Label(loggedinwin, text="Home").pack()
MessageMenuButton = tk.Button(loggedinwin, text="Messaging", command=MessageButtonClick).pack()
maingui = tk.Tk()
userid = tk.StringVar()
passid = tk.StringVar()
UserEnterLabel = tk.Label(maingui, text="Username: ").pack()
UserInput = tk.Entry(maingui, textvariable=userid).pack()
PassEnterLabel = tk.Label(maingui, text="Password: ").pack()
PassInput = tk.Entry(maingui, textvariable=passid).pack()
LoginGo = tk.Button(maingui, text="Login", command=logingo).pack()
SignUpGo = tk.Button(maingui, text="Sign Up", command=SignUp).pack()
maingui.mainloop()
The first problem is that you're creating more than one instance of Tk. Tkinter isn't designed to work that way, and will yield unexpected results. If you need more than one window you need to create instances of Toplevel

Categories