Tkinter gui loginsystem in python getting not deffined errors using .get() - python-3.x

This is my python login system I have attempted to built when I run the check on the user name and password I receive this error : http://pastebin.com/0DPAWx18
I was wondering if it because it is in a another function but I then put it in main as well and that just gave me errors
import tkinter
import time
def main():
global window
window = tkinter.Tk()
window.title("Login")
window.minsize(300,150)
window.configure(background="#7AC5CD")
userlbl = tkinter.Label(window, text="Username")
userlbl.pack()
userinp = tkinter.Entry(window)
userinp.pack()
pwlbl = tkinter.Label(window, text="Password")
pwlbl.pack()
userpw = tkinter.Entry(window)
userpw.pack()
submitbtn = tkinter.Button(text="Submit username and password here", command=check)
submitbtn.pack()
def check():
username = userinp.get()
password = userpw.get()
if username == 1234:
GD_USER = tkinter.Label(window, text="Correct user name")
GD_USER.pack()
else:
BD_USER = tkinter.Label(window, text="Bad username")
BD_USER.pack()
if password == 'test':
GD_PASS = tkinter.Label(window, text="Correct password")
GD_PASS.pack()
entry_YES()
return
else:
BD_PASS = tkinter.Label(window, text="wrong password")
window.mainloop()
def entry_NO():
print("access denied")
time.sleep(5)
close_window
return
def entry_YES():
print("Access granted please wait")
def close_window():
window.destry()
enter code here

That's is because you define userinp in the main function's scope, so it isn't defined the check function. You could make userinp and userpw global, or you could make your app into a class like this, which makes variable passing a lot easier through self.
The __init__ function is called when the class is called, so that can be used as 'main'.
I've put pretty much everything in self, which isn't necessary, but can be useful if you'd want to change any of the created widgets further on in a new function.
The update() function is needed to pack the labels before sleeping.
import tkinter as tk
import time
class App():
def __init__(self):
self.window = tk.Tk()
self.window.title("Login")
self.window.minsize(300,150)
self.window.configure(background="#7AC5CD")
self.userlbl = tk.Label(self.window, text="Username")
self.userlbl.pack()
self.userinp = tk.Entry(self.window)
self.userinp.pack()
self.pwlbl = tk.Label(self.window, text="Password")
self.pwlbl.pack()
self.userpw = tk.Entry(self.window)
self.userpw.pack()
self.submitbtn = tk.Button(text="Submit username and password here", command=self.check)
self.submitbtn.pack()
self.window.mainloop()
def check(self):
self.username = self.userinp.get()
self.password = self.userpw.get()
if self.username == '1234':
self.GD_USER = tk.Label(self.window, text="Correct user name")
self.GD_USER.pack()
else:
self.BD_USER = tk.Label(self.window, text="Bad username")
self.BD_USER.pack()
if self.password == 'test':
self.GD_PASS = tk.Label(self.window, text="Correct password")
self.GD_PASS.pack()
self.entry_YES()
else:
self.BD_PASS = tk.Label(self.window, text="Wrong password")
self.BD_PASS.pack()
self.window.update()
self.entry_NO()
def entry_NO(self):
print("Access denied, wait 5 seconds to try again")
time.sleep(5)
def entry_YES(self):
print("Access granted please wait")
def close_window(self):
window.destroy()
App()
For more info on making your app into a class read this and this question.

Related

Validate Email in Entry widget content more than once - tkinter

I have a code that correctly validates email, but this happens only once. So if the email is invalid, it wont let me validate it again. Is there a way how to validate it over and over?
import tkinter as tk
from tkinter import *
from tkinter import ttk
import re
class Test(tk.Frame):
def __init__(self, root):
self.root = root
self.root.geometry("{}x{}+250+150".format(500, 500))
self.entry()
def testAlphaValue(self, value):
if value.isalpha():
return True
else:
return False
def testEmail(self, email):
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[#]\w+[.]\w{2,3}$'
wdg = self.wdgLst
if(re.search(regex, email)):
return wdg.configure(text='Email is valid')
else:
return wdg.configure(text='Email is invalid')
def entry(self):
self.formFrame = LabelFrame(self.root, bg='grey', bd=1)
self.formFrame.place(x=50, y=50, width=400, height=400)
regEmail = self.root.register(self.testEmail)
regAlpha = self.root.register(self.testAlphaValue)
nameEnt = Entry(self.formFrame)
nameEnt.config(validate="key", validatecommand=(regAlpha, '%S'))
nameEnt.grid(row=0, column=1)
emailEnt = Entry(self.formFrame)
emailEnt.config(validate="focusout", validatecommand=(regEmail, '%P'))
emailEnt.grid(row=0, column=0)
emailLbl = Label(self.formFrame, text='Email', font=("Helvetica", 8))
emailLbl.grid(row=1, column=0)
self.wdgLst = emailLbl
root=tk.Tk()
test = Test(root)
root.mainloop()
Thank you!
Here is a working code for ya which validates email on focus-out event (as you wanted) - (must read the reason with explanation below the code)
import tkinter as tk
from tkinter import *
from tkinter import ttk
import re
class Test(tk.Frame):
def __init__(self, root):
self.root = root
self.root.geometry("{}x{}+250+150".format(500, 500))
self.entry()
def testAlphaValue(self, value):
if value.isalpha():
return True
else:
return False
def checkEmail(self, val):
if re.search(regex, val):
self.wdgLst.configure(text='Email is valid')
return True
else:
self.wdgLst.configure(text='Email is Invalid')
return False
def entry(self):
self.formFrame = LabelFrame(self.root, bg='grey', bd=1)
self.formFrame.place(x=50, y=50, width=400, height=400)
regEmail = self.root.register(self.checkEmail)
regAlpha = self.root.register(self.testAlphaValue)
nameEnt = Entry(self.formFrame)
nameEnt.config(validate="key", validatecommand=(regAlpha, '%S'))
nameEnt.grid(row=0, column=1)
emailEnt = Entry(self.formFrame)
emailEnt.config(validate="focusout", validatecommand=(regEmail, '%P'))
emailEnt.grid(row=0, column=0)
emailLbl = Label(self.formFrame, text='Email', font=("Helvetica", 8))
emailLbl.grid(row=1, column=0)
self.wdgLst = emailLbl
root=tk.Tk()
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[#]\w+[.]\w{2,3}$'
test = Test(root)
root.mainloop()
***REASON FOR THE ISSUE ***
From what I got to know about the issue, there seems to be a rule which is::
The function registered to the validate command must return either True or False.
In any other case, if the function returns something else,
it DISABLES the validation for the respected widget.
In your code you were making it return wdg.configure(<something here>) which was disabling the validation right after the first run.
You can also use the method suggested by #ShaneLoyd above if you wish to change your approach but if you just want to stick to validate commands, go with the above code.
I can't explain why your code doesn't work except that perhaps the Entry widget must only allow the validate code to run once. This might work for your needs.
import tkinter as tk
from tkinter import *
from tkinter import ttk
import re
class Test(tk.Frame):
def __init__(self, root):
self.root = root
self.root.geometry("{}x{}+250+150".format(500, 500))
self.entry()
def testAlphaValue(self, value):
if value.isalpha():
return True
else:
return False
def testEmail(self, sv):
email = sv.get()
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[#]\w+[.]\w{2,3}$'
wdg = self.wdgLst
if (re.search(regex, email)):
return wdg.configure(text='Email is valid')
else:
return wdg.configure(text='Email is invalid')
def entry(self):
self.formFrame = LabelFrame(self.root, bg='grey', bd=1)
self.formFrame.place(x=50, y=50, width=400, height=400)
sv_email = StringVar()
sv_email.trace("w", lambda name, index, mode,
sv=sv_email: self.testEmail(sv_email))
regAlpha = self.root.register(self.testAlphaValue)
nameEnt = Entry(self.formFrame)
nameEnt.config(validate="key", validatecommand=(regAlpha, '%S'))
nameEnt.grid(row=0, column=1)
emailEnt = Entry(self.formFrame)
emailEnt.config(textvariable=sv_email)
emailEnt.grid(row=0, column=0)
emailLbl = Label(self.formFrame, text='Email', font=("Helvetica", 8))
emailLbl.grid(row=1, column=0)
self.wdgLst = emailLbl
root = tk.Tk()
test = Test(root)
root.mainloop()

sending self to callback function outside of the class

I have class GUI and a button, the button press needs to activate a function that not belong to class GUI but needs to run some of the GUI class members function.
how to I do that?
this is my button creation:
tk.Button(self.top_frame, text="connect to server", var=self, command=connect_to_server)
and this is the function:
def connect_to_server(gui):
res = False
try:
# Create a socket object
# write_to_log("Socket successfully created")
ans = s.connect((SERVER_IP, PORT))
if ans is None:
gui.write_to_log('connection to server establish')
gui.connection.configure(state="disable")
res = True
tk.Label(gui.top_frame, text="Connected", bg="green").grid(row=0, column=1)
gui.chk_smds_state.set(tk.TRUE)
else:
gui.write_to_log('connection failed')
return res
message = receive(s)
# write_to_log(str(message, 'ascii'))
gui.write_to_log(message)
res = res
except socket.error as err:
message = f"socket creation failed with error %s" % err
gui.connection.configure(bg='red')
gui.write_to_log(message)
return res
def main():
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Edit aaded the main function for the scop understanding
Here is a basic example of what you are looking for. On button press, it activates function which is defined outside the class and set the text to the label
from Tkinter import Tk, Label, Button
def set_label_text():
my_gui.label_to_set.config(text="New text")
class MyFirstGUI:
def __init__(self, master):
self.button = Button(master, text="Click me", command=set_label_text)
self.button.pack()
self.label_to_set = Label(master)
self.label_to_set.pack()
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

how do i get information passed between the subroutines while using tkinter python

Basically, I want to access and use the variables in the mainlogin function, from the loginbuttonclicked.
def mainlogin():
screen4 = Tk()
screen4.geometry('600x400')
screen4.title('the main menu')
screen4.bg = 'red'
global username_verify
global password_verify
username_verify = StringVar()
password_verify = StringVar()
label_username = Label(text="Username")
label_password = Label(text="Password")
username_mainlogin_entry = Entry(textvariable=username_verify)
password__mainlogin_entry = Entry(textvariable=password_verify, show="*")
label_username.grid(row=0, sticky=E)
label_password.grid(row=1, sticky=E)
username_mainlogin_entry.grid(row=0, column=1)
password__mainlogin_entry.grid(row=1, column=1)
checkbox = Checkbutton(text="Keep me logged in")
checkbox.grid(columnspan=2)
checkbox = Checkbutton(text='New user', command=newuserbtn)
checkbox.grid(columnspan=3)
checkbox = Checkbutton(text='override', command=mainprogram)
checkbox.grid(columnspan=4)
logbtn = Button(text="Login", command=loginbtnclicked)
logbtn.grid(columnspan=2)
def loginbtnclicked():
username_entry = StringVar()
password_entry = StringVar()
username = username_entry.get()
password = username_entry.get()
if username == 'a' and password == 'p':
mainprogram()
else:
print('oh')
You will have to restructure your code to achieve that.
You either use global variables or you use a class structure.
Global variable:
def mainlogin():
global var_to_access
var_to_access=10
def loginbtnclicked():
print(var_to_access)
Class structure:
class My_Class:
def __init__():
pass
def mainlogin():
self.var_to_access=10
def loginbtnclicked():
print(self.var_to_access)

How can i validate in python if a username and password already exist in mySQL Database?

Hi so I've been working on this project about a day now(New to python and mySQL)
So my question is how i can see if the input user credentials in the textbox is already a registered user?
So far I've managed to connect it to the database and store some values inside the database but i cant seem to figure out how i can scan that database and see if the user info are valid when the login button is pressed.
from tkinter import*
from tkinter import messagebox
import mysql.connector
import time
import datetime
import random
w = 300
h = 2
def register_user():
global username_info
global password_info
if len(username.get()) == 0 and len(password.get()) == 0:
print("Please fill in the Missing Info")
if len(username.get()) == 0 and len(password.get()) != 0 :
print("Please Enter a Username")
elif len(username.get()) != 0 and len(password.get()) == 0:
print("Please enter a Password")
else:
username_info = username.get()
password_info = password.get()
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="loginsystem"
)
mycursor = mydb.cursor()
sqlFormula = "INSERT INTO users (Username, Password) VALUES (%s, %s)"
insertvar = (username_info, password_info)
user1 = ("Joshua", "Cuyugan")
mycursor.execute(sqlFormula, insertvar)
mydb.commit()
username.set("")
password.set("")
def register():
global screen1
screen.withdraw()
screen1 = Toplevel(screen)
screen1.title("Registration")
screen1.geometry("500x250+700+350")
global username
global password
global username_entry
global password_entry
username = StringVar()
password = StringVar()
Label(screen1, text = " Please Enter Your Details Below", bg = "black", width = w , height = h, font = ("Calibri", 20) , fg = "white").pack()
Label(screen1, text = "").pack()
Label(screen1, text = "Username").place(x=220, y=85)
username_entry = Entry(screen1, textvariable = username, width="50").place(x=100, y=110)
Label(screen1, text = "Password").place(x=220, y=135)
password_entry = Entry(screen1, textvariable = password, width="50").place(x=100, y=160)
Button(screen1, text= "Register", height="1", width="20", command = register_user).place(x=80, y=200)
Button(screen1, text="Cancel", height="1", width="20", command= on_closereg).place(x=270, y=200)
screen1.protocol("WM_DELETE_WINDOW", on_closereg)
def login():
global screen2
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="loginsystem"
)
mycursor = mydb.cursor()
sql_select_Query = "select * from users"
mycursor.execute(sql_select_Query)
records = mycursor.fetchall()
for row in records:
print("Username" , row[1],)
print("Password", row[2], "\n" )
mycursor.close()
screen.withdraw()
screen2 = Toplevel(screen)
screen2.title("HOT or SUPER HOT")
screen2.geometry("800x600+550+220")
screen2.protocol("WM_DELETE_WINDOW", on_close)
def checker():
if len(username.get()) == 0 and len(password.get()) == 0:
print("Please fill in the Missing Info")
def on_close():
screen2.withdraw()
screen.update()
screen.deiconify()
screen.lift()
def on_closereg():
screen1.withdraw()
screen.update()
screen.deiconify()
screen.lift()
def verify():
global name
global userlogcred
global userpascred
userlogcred = username_verify.get()
userpascred = password_verify.get()
loadname = ("SELECT Username FROM users WHERE Username =%s")
loadpass = ("SELECT Password FFROM users WHERE Password =%s")
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="loginsystem"
)
mycursor = mydb.cursor()
if len(username_verify.get()) == 0 and len(password_verify.get()) == 0:
print("Please fill in the Missing Info")
if len(username_verify.get()) == 0 and len(password_verify.get()) != 0 :
print("Please Enter a Username")
elif len(username_verify.get()) != 0 and len(password_verify.get()) == 0:
print("Please enter a Password")
else:
mycursor.execute(loadname, userlogcred)
mycursor.execute(loadpass, userpascred)
logincheck = mycursor.fetchone()
loginpasscheck = mycursor.fetchone()
if logincheck is None:
print("Sorry, could not find you in the database\nOr it just isn't working")
if logincheck is not None and loginpasscheck is None:
print("Please Enter your Password")
elif logincheck is None and loginpasscheck is not None:
print("Please enter Your Username")
else:
print("pass\nSuccessfully loaded {} from the database".format(username_verify.get()))
def main_Screen():
global screen
screen = Tk()
screen.geometry("600x300+650+350")
screen.title("Login System")
Label(text = "Login System" , bg = "black", width = w , height = h, font = ("Calibri", 20) , fg = "white").pack()
Label(text = "").pack()
Button(text = "Login", height = h, width = "30", command = verify).place(x=50 , y=200)
Label(text = "").pack()
Button(text = "Register" ,height = h, width = "30", command = register).place(x=320 , y=200)
global username_verify
global password_verify
username_verify = StringVar()
password_verify = StringVar()
Label(screen, text = "Username").place(x=265, y = 90)
username_entry1 = Entry(screen, textvariable = username_verify, width = "80").place(x=57, y=110)
Label(screen, text="Password").place(x=267, y=140)
password_entry1 = Entry(screen, textvariable = password_verify, width = "80").place(x=57, y=160)
screen.mainloop()
main_Screen()
print("Hello World")
Update I Found this code and I'm trying to apply it to my project where in this code compares the input value inside the textbox to the database data and it checks if the datas are already present if they are it then sends you to another form.
def verify():
global name
loadname = ("SELECT Username FROM users WHERE Username =%s")
loadpass = ("SELECT Password FFROM users WHERE Password = %s")
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="loginsystem"
)
mycursor = mydb.cursor()
if len(username_verify.get()) == 0 and len(password_verify.get()) == 0:
print("Please fill in the Missing Info")
if len(username_verify.get()) == 0 and len(password_verify.get()) != 0 :
print("Please Enter a Username")
elif len(username_verify.get()) != 0 and len(password_verify.get()) == 0:
print("Please enter a Password")
else:
mycursor.execute(loadname, username_verify.get())
mycursor.execute(loadpass, password_verify.get())
logincheck = mycursor.fetchone()
loginpasscheck = mycursor.fetchone()
if logincheck is None:
print("Sorry, could not find you in the database\nOr it just isn't working")
if logincheck is not None and loginpasscheck is None:
print("Please Enter your Password")
elif logincheck is None and loginpasscheck is not None:
print("Please enter Your Username")
else:
print("pass\nSuccessfully loaded {} from the database".format(login))
but I encountered this erro please help.
Traceback (most recent call last):
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/lenovo/PycharmProjects/Pylog/App.py", line 141, in verify
mycursor.execute(loadname, username_verify.get())
File "C:\Users\lenovo\PycharmProjects\Pylog\venv\lib\site-packages\mysql\connector\cursor.py", line 569, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\lenovo\PycharmProjects\Pylog\venv\lib\site-packages\mysql\connector\connection.py", line 553, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\lenovo\PycharmProjects\Pylog\venv\lib\site-packages\mysql\connector\connection.py", line 442, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1
Hello World
Update I put the username_verify.get() values into variables still didn't work and it still posts the same error.
import mysql.connector as sql
class connections:
__HOST = 'localh`o`st'
__USERNAME = 'root'
__PASSWORD = ''
__DATABASE = 'testing'
def __init__(self):
self.con = sql.connect(host=connections.__HOST,user=connections.__USERNAME,password=connections.__PASSWORD,database=connections.__DATABASE)
def connect_database(self,username,password):
#append password and username in the emptey list below for later checkings
mypassword_queue =[]
sql_query = "SELECT *FROM users WHERE first_name ='%s' AND password ='%s'" % (username, password)
mycursor = self.con.cursor()
try:
mycursor.execute(sql_query)
myresults =mycursor.fetchall()
for row in myresults:
for x in row:
mypassword_queue.append(x)
except:
print('error occured')
if (username and password) in mypassword_queue:
print('there is something')
else:
print('there is no anything')
self.con.close()
root = connections()
#---you must have created a database with choice of your database name for this case it is testing
#---- the data inside has name as tumusiime and password 1234
root.connect_database('tumusiime','1234')
I will give you a code that works for me for all querys with mysql.connector
**config= {'user': your_user',
'password': 'your_pass',
'host': 'ip_of_your_db',
'database': 'name_of_your_db',
'raise_on_warnings': True}
def run_query(self,query):
try:
conn = mysql.connector.connect(**self._config)
if conn.is_connected():
print('run_query: Connecting MySql Db')
cur = conn.cursor()
cur.execute(query)
r= cur.fetchall()
return r
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("run_query: Error in username or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("run_query: Dabatase doesn't exist")
else:
print(err)
finally:
conn.commit()
conn.close()
and each Query need to have this format
query='SELECT * FROM {}'.format("your_db.your_table")
answer=self.run_query(query)

Chat Client: tkinter text widget not updating after pressing send

I am creating a chat server/client using PodSixNet and tkinter and my problem is when I press 'send' to send a message to the other users in the chat room it does not display in the the Text widget.
If I use the commented out code:print(data['who'] + ": " + data['message']) the message will print just fine on the console but I just cannot get it to appear on the GUI. I don't really know how to go about solving this issue. Below is the code of my client, it is python 3.6.
Chat Client
import sys
from time import sleep
from sys import stdin, exit
from tkinter import *
from PodSixNet.Connection import connection, ConnectionListener
from _thread import *
root = Tk()
root.title("Chat")
line1 = 1.0
class Client(ConnectionListener):
def __init__(self, host, port):
self.Connect((host, port))
print("Chat client started")
print("Ctrl-C to exit")
# get a nickname from the user before starting
print("Enter your nickname: ")
connection.Send({"action": "nickname", "nickname": stdin.readline().rstrip("\n")})
messages = Text(root)
messages.pack()
userInput = StringVar()
textField = Entry(root, text = userInput)
textField.pack(side = BOTTOM, fill = X)
self.message = messages
self.inputField = textField
sendButton = Button(root, text = "Send", command = lambda: self.InputLoop())
sendButton.pack(side = LEFT)
root.mainloop()
def Loop(self):
connection.Pump()
self.Pump()
def InputLoop(self):
connection.Send({"action": "message", "message": self.inputField.get()})
#######################################
### Network event/message callbacks ###
#######################################
def Network_players(self, data):
print("*** players: " + ", ".join([p for p in data['players']]))
def Network_message(self, data):
global line1
# print(data['who'] + ": " + data['message'])
msgGet = data['who'] + ": " + data['message']
self.message.insert(END, msgGet)
line1 += 1.0
# built in stuff
def Network_connected(self, data):
print("You are now connected to the server")
def Network_error(self, data):
print('error:', data['error'][1])
connection.Close()
def Network_disconnected(self, data):
print('Server disconnected')
exit()
if len(sys.argv) != 2:
print("Usage:", sys.argv[0], "host:port")
print("e.g.", sys.argv[0], "localhost:31425")
else:
host, port = sys.argv[1].split(":")
c = Client(host, int(port))
while 1:
c.Loop()
sleep(0.001)
EDIT: Here is the code of the server, in case it is needed.
Chat Server
import sys
from time import sleep, localtime
from weakref import WeakKeyDictionary
from PodSixNet.Server import Server
from PodSixNet.Channel import Channel
class ClientChannel(Channel):
"""
This is the server representation of a single connected client.
"""
def __init__(self, *args, **kwargs):
self.nickname = "anonymous"
Channel.__init__(self, *args, **kwargs)
def Close(self):
self._server.DelPlayer(self)
##################################
### Network specific callbacks ###
##################################
def Network_message(self, data):
self._server.SendToAll({"action": "message", "message": data['message'], "who": self.nickname})
def Network_nickname(self, data):
self.nickname = data['nickname']
self._server.SendPlayers()
class ChatServer(Server):
channelClass = ClientChannel
def __init__(self, *args, **kwargs):
Server.__init__(self, *args, **kwargs)
self.players = WeakKeyDictionary()
print('Server launched')
def Connected(self, channel, addr):
self.AddPlayer(channel)
def AddPlayer(self, player):
print("New Player" + str(player.addr))
self.players[player] = True
self.SendPlayers()
print("players", [p for p in self.players])
def DelPlayer(self, player):
print("Deleting Player" + str(player.addr))
del self.players[player]
self.SendPlayers()
def SendPlayers(self):
self.SendToAll({"action": "players", "players": [p.nickname for p in self.players]})
def SendToAll(self, data):
[p.Send(data) for p in self.players]
def Launch(self):
while True:
self.Pump()
sleep(0.0001)
# get command line argument of server, port
if len(sys.argv) != 2:
print("Usage:", sys.argv[0], "host:port")
print("e.g.", sys.argv[0], "localhost:31425")
else:
host, port = sys.argv[1].split(":")
s = ChatServer(localaddr=(host, int(port)))
s.Launch()
EDIT The following doesn't seem to fix the problem.
You probably need to tell the tkinter.Text widget to use all the available space by calling pack as follows:
messages.pack(fill=BOTH, expand=1)
Here's a stripped-down version of the client without the network part. I used it to test the above solution to find that it doesn't make a difference.
from tkinter import *
root = Tk()
messages = Text(root)
messages.pack() # (fill=BOTH, expand=1)
userInput = StringVar()
textField = Entry(root, text = userInput)
textField.pack(side = BOTTOM, fill = X)
def on_send():
msgGet = textField.get()
messages.insert(END, msgGet)
sendButton = Button(root, text = "Send", command = on_send)
sendButton.pack(side = LEFT)
root.mainloop()

Resources