Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm working on a password manager using python in the PyCharm IDE. I am working with a database to store the passwords, which makes a .db file in the project folder. Then i wanted to clear that file as i wanted a clear db to work with. So i deleted the .db file from my folder, thinking it would create a new file and work fine. However, it did not.
I get the following error message:
Traceback (most recent call last):
File "C:/Users/Gebruiker/PycharmProjects/evault/main.py", line 246, in <module>
open_vault()
File "C:/Users/Gebruiker/PycharmProjects/evault/main.py", line 235, in open_vault
Label(vault, text=(array[i][1]), font=("Helvetica", 12)).place(x=400, y=400)
IndexError: list index out of range
I tried reverting changes with local history, but that wouldn't work for me either (or i just didn't understand)
[EDIT] Does it maybe have something to do with a new, so empty, database being created and then trying to display the contents of that database but failing as there are none? The deleted database file by me had contents, which did display. Might also be completely wrong, idk.
If it would help, this is my whole project code:
from tkinter import *
from tkinter import messagebox
from random import choice
import array
import sqlite3
import hashlib
import pyperclip as pc
from functools import partial
# Database
with sqlite3.connect("vault.db") as db:
cursor = db.cursor()
service = None
username = None
password = None
cursor.execute("""
CREATE TABLE IF NOT EXISTS vault (
id INTEGER PRIMARY KEY,
service TEXT NOT NULL,
username TEXT NOT NULL,
password TEXT NOT NULL);
""")
def hash_password(pw):
hash = hashlib.md5(pw)
hash = hash.hexdigest()
return hash
def validate_login():
# getting form data
uname = username_log.get()
pwd = master_key.get()
# applying empty validation
if uname == '' or pwd == '':
message.set("Please fill in all the fields")
else:
if uname == "Laurens" and pwd == "password":
login_screen.destroy()
open_vault()
else:
message.set("Wrong username or password")
def generate_password():
len = 12
digits = '0123456789'
chars = 'abcdefghijklmn' \
'opqrstuvwxyz'
up = chars.upper()
special = '_!$%&?'
all = digits + chars + up + special
password = ''.join(
choice(all) for i in range(len)
)
# print out password
print(password)
save = messagebox.askyesnocancel("Generated password", f"Your generated safe password is: \n \n {password} "
f"\n \n Click yes to copy to clipboard"
f"\n and click no to generate a new password.")
if save:
# 'Yes' > copy to clipboard
pc.copy(password)
elif not save and save is not None:
# 'No' > generate new password
generate_password()
else:
# 'Cancel'
pass
def save_credentials():
service_input = service.get()
username_input = username.get()
password_input = password.get()
insert_fields = ("""INSERT INTO vault(service, username, password)
VALUES(?, ?, ?)
""")
cursor.execute(insert_fields, (service_input, username_input, password_input))
db.commit()
print(db)
open_vault()
def remove_credentials(input):
cursor.execute("DELETE FROM vault WHERE id = ?", (input,))
db.commit()
open_vault()
def register_credentials():
global service
global username
global password
vault.destroy()
register_screen = Tk()
register_screen.resizable(False, False)
register_screen.title("Login")
register_screen.geometry("350x500")
register_screen.configure(bg='#212121')
service = StringVar()
username = StringVar()
password = StringVar()
# Service Label
Label(register_screen, text="Name of service: ", bg='#212121', fg='#ABABAB').place(relx=0.5, y=100, anchor=CENTER)
# Service textbox
Entry(register_screen, textvariable=service).place(width=180, height=30, relx=0.5, y=140, anchor=CENTER)
# Username Label
Label(register_screen, text="Username: ", bg='#212121', fg='#ABABAB').place(relx=0.5, y=200, anchor=CENTER)
# Username textbox
Entry(register_screen, textvariable=username).place(width=180, height=30, relx=0.5, y=240, anchor=CENTER)
# Password Label
Label(register_screen, text="Password: ", bg='#212121', fg='#ABABAB').place(relx=0.5, y=300, anchor=CENTER)
# Password textbox
Entry(register_screen, textvariable=password).place(width=180, height=30, relx=0.5, y=340, anchor=CENTER)
# Generate password button
Button(register_screen, text="Generate safe password", bg='#ABABAB', fg='#000000', command=generate_password).place(
width=140, height=30, relx=0.5, y=400, anchor=CENTER)
# Save credentials button
Button(register_screen, text="Save credentials", bg='#673AB7', fg='#FFFFFF', command=save_credentials).place(
width=150, height=40, relx=0.5, y=460, anchor=CENTER)
register_screen.mainloop()
def login_screen():
global login_screen
global message
global username_log
global master_key
login_screen = Tk()
login_screen.resizable(False, False)
login_screen.title("Login")
login_screen.geometry("300x210")
login_screen.configure(bg='#212121')
# declaring variable
username_log = StringVar()
master_key = StringVar()
message = StringVar()
# Creating layout of login form
Label(login_screen, width="300", text="Please enter username and master key", bg="#673AB7", fg="#FFFFFF").pack()
# Username Label
Label(login_screen, text="Username: ", bg='#212121', fg='#ABABAB').place(x=20, y=40)
# Username textbox
Entry(login_screen, textvariable=username_log).place(x=90, y=42)
# Password Label
Label(login_screen, text="Master key: ", bg='#212121', fg='#ABABAB').place(x=20, y=80)
# Password textbox
Entry(login_screen, textvariable=master_key, show="*").place(x=90, y=82)
# Label for displaying login status[success/failed]
Label(login_screen, text="", textvariable=message, bg='#212121', fg='#ff0000').place(relx=0.5, y=125, anchor=CENTER)
# Login button
Button(login_screen, text="Login", width=10, height=1, bg='#673AB7', fg='#FFFFFF', command=validate_login).place(
x=110, y=150)
login_screen.mainloop()
def open_vault():
global vault
vault = Tk()
vault.resizable(False, False)
vault.title("Evault")
vault.geometry("750x500")
vault.configure(bg='#212121')
Label(vault, text="Service", bg='#212121', fg='#ABABAB').place(relx=0.2, y=75)
Label(vault, text="Username", bg='#212121', fg='#ABABAB').place(relx=0.45, y=75)
Label(vault, text="Password", bg='#212121', fg='#ABABAB').place(relx=0.7, y=75)
Button(vault, text="Register new credentials", bg='#673AB7', fg='#FFFFFF', command=register_credentials).place(
width=150, height=40, relx=0.5, y=450, anchor=CENTER)
cursor.execute('SELECT * FROM vault')
if cursor.fetchall() != None:
i = 0
while True:
cursor.execute('SELECT * FROM vault')
array = cursor.fetchall()
Label(vault, text=(array[i][1]), font=("Helvetica", 12)).place(x=400, y=400)
i += 1
cursor.execute('SELECT * FROM vault')
if len(cursor.fetchall()) <= i:
break
vault.mainloop()
open_vault()
The error is being thrown by this:
cursor.execute('SELECT * FROM vault')
if cursor.fetchall() != None:
i = 0
while True:
cursor.execute('SELECT * FROM vault')
array = cursor.fetchall()
Label(vault, text=(array[i][1]), font=("Helvetica", 12)).place(x=400, y=400)
i += 1
cursor.execute('SELECT * FROM vault')
if len(cursor.fetchall()) <= i:
break
I confess I don't understand what this code is supposed to do. Why does it repeatedly execute the same query? You probably want something like this:
cursor.execute("SELECT * FROM vault")
START_HEIGHT=400
LINE_HEIGHT=50
for i, row in enumerate(cursor.fetchall()):
line_pos = START_HEIGHT + i * LINE_HEIGHT
Label(vault, text=row[1]).place(x=400,y=line_pos)
i.e. just iterate over the rows returned by the cursor directly.
If that is still throwing an error, you need to do some debugging: print what cursor.fetchall() actually returns. (Specifically, print list(cursor.fetchall()) in case it's an iterator.)
Related
The program I'm currently working on should take two inputs given during a function and use them during another function to verify a user, this is done using Tkinter and SQL but the SQL either throws up an error or does not print or progress at all despite it being coded to do so, currently the result it should give is printing True when the password give and the result of the SQL match, I'm wondering if either the SQL is jankey or the way I've set up the variables is, either way I'm beating my head against trying to figure it out so any help would be appreciated, I'm fairly sure the problem is only with the submitlog fuction if that narrows down any issues.
import sqlite3 #necessary to use databse searching
import os #necessary to check the date listed by the system
from tkinter import * #necessary to use the GUI design features
from tkinter import messagebox #needed for message boxes
login = False #needed to start the login procedure
root =Tk() #defines the foundations for a created page
connection1 = sqlite3.connect("Login.db") #code to read the database and allow crossreferencing of passwords
#connection2
Username = ""
Password = ""
def submitlog(): #a function that will compare and entered username and password with present passwords on the login database
cursor1 = connection1.cursor()
for row in cursor1.execute('SELECT Password FROM Login WHERE Username = "{}"'.format(Username.replace('"','""')), (Username))[0]:
if row == Password:
print(True)
else:
print(Username)
print(Password)
print(row)
def logOut():
root.destroy
exit()
def loginpage(): #defines the creation of a login page
root.geometry("1000x700")
root.resizable(False, False)
root.configure(background = "Black")
#creation of text frames
frame_heading = Frame(root)
frame_heading.grid(row=0, column=0, columnspan=2, padx=30, pady=5)
#creation of entry frames
frame_entry = Frame(root)
frame_entry.grid(row=1, column=0, columnspan=2, padx=10, pady=10)
Label(frame_heading, text="Please log in", font=("Arial", 16)).grid(row=0,column=0,padx=0,pady=5) #heading label
#entry labels
Label(frame_entry, text="Username: ").grid(row=0,column=0,padx=10,pady=10)
Label(frame_entry, text="Password: ").grid(row=1,column=0,padx=10,pady=10)
#text entry fields
UserName = Entry(frame_entry,width=30, bg = "white")
UserName.grid(row=0, column=1, padx=5, pady=5)
PassWord = Entry(frame_entry,width=30, bg = "white")
PassWord.grid(row=1, column=1, padx=5, pady=5)
#placing the submit and log off buttons
submit_button = Button(root, text = "Submit", width =10, command= submitlog)
submit_button.grid(row=2,column=0,padx=0,pady=5)
logout_button = Button(root, text = "Log out", width = 10, command = logOut)
logout_button.grid(row=2,column=1,padx=0,pady=5)
root.mainloop()
Username = UserName.get()
Password = PassWord.get()
return Username and Password
previous attempts to rectify involve me trying to update the variables in both functions as well as running the login page outside of a function but all attempts resulted in either and an error or no activity at all
There's no need to use a for loop. Assuming usernames are unique, the query either returns a row or it doesn't. So you can call cursor1.fetchone() to get that row, then check the password.
You also need to get the username and password from the entry fields when you call submitlog(), not when you first create them.
def submitlog(): #a function that will compare and entered username and password with present passwords on the login database
cursor1 = connection1.cursor()
Username = UserName.get()
Password = PassWord.get()
cursor1.execute('SELECT Password FROM Login WHERE Username = ?', (Username,))
row = cursor1.fetchone()
if row and row[0] == Password:
print(True)
else:
print(Username)
print(Password)
print(row)
You'll need to add global UserName, PassWord to loginpage() so that the variables can be accessed from submitlog().
BTW, return Username and Password is not the way you return multiple values from a function. That should be return Username, Password. But I doubt the return value is used, so you don't need to return anything.
Maybe this helps
query = 'SELECT Password FROM Login WHERE Username = ?'
cursor.execute(query, (Username,))
results = cursor.fetchall()
for row in results:
if row[0] == Password:
print(True)
Thanks Barmar for the helpful comments.
I have built a login system using Tkinter and Sqlite3 for Python and I need to move on to another section of code once the login flow is complete. At the point in the 'test' function where I've added a comment, I need a separate python file (eg somefile.py) to run its code. How is best to do this? Your help is appreciated! Code below:
from tkinter import *
import Check_credentials as check
import New_user_screen as create
def test():
username = user.get()
password = pword.get()
global valid
valid = False
valid=check.check_user(username,password)
print(valid)
if valid == True:
login.destroy()
'launch main program' #Here is where i need the next section of the program to be run but ideally not as another function in this proram
print('Incorrect login getails\nPlease try again!')
def screen():
global login
login = Tk()
login.title('User Login')
login.geometry('300x180')
login.configure(background = 'white')
global user
global pword
message = Label(login,
text = 'Please enter username and password below',
bg='white')
message.pack()
label1 = Label(login,
text = 'Username',
bg='white')
label1.place(x=0,y=50)
user = Entry(login)
user.place(x=100,y=50)
label2 = Label(login,
text = 'Password',
bg='white')
label2.place(x=0,y=90)
pword = Entry(login)
pword.place(x=100,y=90)
confirm = Button(login,
text='Sign In',
fg='white',
bg='blue',
command = test)
confirm.place(x=50,y=130)
new = Button(login,
text='New User',
fg='white',
bg='blue',
command = create.screen)
new.place(x=120,y=130)
When the login is valid, it will go to the the function greeting in the class Main
from tkinter import *
import Check_credentials as check
import New_user_screen as create
class Login:
def test():
username = user.get()
password = pword.get()
global valid
valid = False
valid=check.check_user(username,password)
print(valid)
if valid == True:
login.destroy()
Main.greeting() #Here is where i need the next section of the program to be run but ideally not as another function in this proram
def screen():
global login
login = Tk()
login.title('User Login')
login.geometry('300x180')
login.configure(background = 'white')
global user
global pword
message = Label(login,
text = 'Please enter username and password below',
bg='white')
message.pack()
label1 = Label(login,
text = 'Username',
bg='white')
label1.place(x=0,y=50)
user = Entry(login)
user.place(x=100,y=50)
label2 = Label(login,
text = 'Password',
bg='white')
label2.place(x=0,y=90)
pword = Entry(login)
pword.place(x=100,y=90)
confirm = Button(login,
text='Sign In',
fg='white',
bg='blue',
command = test)
confirm.place(x=50,y=130)
new = Button(login,
text='New User',
fg='white',
bg='blue',
command = create.screen)
new.place(x=120,y=130)
class Main:
def greeting():
print("You Have Logged In Successfully")
I'm trying to make a simple tkinter program where there's entries to put your username, email, and password and I am trying to make it check if there a username already exists and it gives me this error. I know there has been other questions about it on stackoverflow but those did not help me out.
import mysql.connector
from tkinter import *
root = Tk()
root.title("Login")
root.iconbitmap("profile.ico")
db = mysql.connector.connect(
db = "pythonlogin",
host="127.0.0.1",
user="root",
password="[password]"
)
cursor = db.cursor()
usernameLabel = Label(root, text='Username: ')
emailLabel = Label(root, text='Email: ')
passwordLabel = Label(root, text='Password: ')
usernameEntry = Entry(root, width=30)
emailEntry = Entry(root, width=30)
passwordEntry = Entry(root, width=30)
usernameLabel.grid(row=0, column=0)
emailLabel.grid(row=1, column=0)
passwordLabel.grid(row=2, column=0)
usernameLabel.config(font=("Roboto", 12))
emailLabel.config(font=("Roboto", 12))
passwordLabel.config(font=("Roboto", 12))
usernameEntry.grid(row=0, column=1)
emailEntry.grid(row=1, column=1)
passwordEntry.grid(row=2, column=1)
class userInfo():
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
def addInfoToDB(self):
query = "INSERT INTO pylogin (Username, Email, Password) VALUES (%s, %s, %s)"
values = (self.username, self.email, self.password)
cursor.execute(query, values)
db.commit()
print(cursor.rowcount, "record inserted.")
errorLabel = Label(root)
errorLabel.grid(row=4, column=1)
def submitInfo():
fetchInfo = cursor.fetchall()
if usernameEntry.get() == "" or emailEntry.get() == "" or passwordEntry.get() == "":
errorLabel.config(text="Error: Couldn't get value of all entries", fg="red")
if (usernameEntry.get(),) in fetchInfo:
errorLabel.config(text="Username already exists in the database!")
else:
errorLabel.config(text="Success!", fg="green")
details = userInfo(usernameEntry.get(), emailEntry.get(), passwordEntry.get())
details.addInfoToDB()
submitButton = Button(root, text="Submit", command=submitInfo)
submitButton.grid(row=3, column=1, ipadx=50)
submitButton.config(font=("Roboto", 10))
root.mainloop()
In the submitInfo method, you have fetchInfo = cursor.fetchall() but no query has been executed.
>>> import mysql.connector as mc
>>> conn = mc.connect(database='test')
>>> cur = conn.cursor()
>>> cur.fetchall()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
mysql.connector.errors.InterfaceError: No result set to fetch from
You need to execute a SELECT query before you can fetch a result.
It looks as if you are checking whether the username entered exists in the database, so you probably want to query the database for that name:
def submitInfo():
if usernameEntry.get() == "" or emailEntry.get() == "" or passwordEntry.get() == "":
errorLabel.config(text="Error: Couldn't get value of all entries", fg="red")
# Query the database for a row with a matching username
stmt = """SELECT Username, Email, Password FROM pylogin WHERE Username = %s"""
cursor.execute(stmt, (usernameEntry.get(),))
# There should be at most one matching row, so we can use
# the cursor's fetchone method to retrieve it.
row = cursor.fetchone()
if row:
errorLabel.config(text="Username already exists in the database!")
else:
errorLabel.config(text="Success!", fg="green")
details = userInfo(usernameEntry.get(), emailEntry.get(), passwordEntry.get())
details.addInfoToDB()
The 4 buttons (insert, delete, update, get) worked perfectly when I only have a student table in the MySQL database. after I try to add the faculty and college in Python GUI and run, The 4 buttons won't work.
I created the same 4 buttons under each table in the python GUI.
def insert():
fid = e_fid.get()
fname = e_fname.get();
fsalary = e_fsalary.get();
if(fid=="" or fsalary=="" or fname==""):
MessageBox.showinfo("Insert status", "All fields are required")
else:
con = mysql.connect(host="localhost", user="root", password="", database="test0910")
cursor = con.cursor()
cursor.execute("insert into faculty values('"+ fid + "','"+ fname +"','"+ fsalary +"')")
cursor.execute("commit");
e_fid.delete(0, 'end')
e_fname.delete(0, 'end')
e_fsalary.delete(0, 'end')
show()
MessageBox.showinfo("Insert Status", "Inserted Successfully");
con.close();
def insert():
id = e_id.get()
name = e_name.get();
address = e_address.get();
if(id=="" or name=="" or address==""):
MessageBox.showinfo("Insert status", "All fields are required")
else:
con = mysql.connect(host="localhost", user="root", password="", database="test0910")
cursor = con.cursor()
cursor.execute("insert into student values('"+ id + "','"+ name +"','"+ address +"')")
cursor.execute("commit");
e_id.delete(0, 'end')
e_name.delete(0, 'end')
e_address.delete(0, 'end')
show()
MessageBox.showinfo("Insert Status", "Inserted Successfully");
con.close();
root = Tk()
root.geometry("600x700")
root.title("Python+Tkinter+MySQL")
faculty = Label(root, text='Faculty', font=('bold', 15))
faculty.place(x=130, y=250);
fid = Label(root, text='Enter ID', font=('bold', 10))
fid.place(x=20, y=290);
fname = Label(root, text='Enter Name', font=('bold', 10))
fname.place(x=20, y=320);
fsalary = Label(root, text='Enter Salary', font=('bold', 10))
fsalary.place(x=20, y=350);
e_fid = Entry()
e_fid.place(x=150, y=290)
e_fname = Entry()
e_fname.place(x=150, y=320)
e_fsalary = Entry()
e_fsalary.place(x=150, y=350)
insert = Button(root, text="Insert", font=("italic", 10), bg="white", command=insert)
insert.place(x=40, y=390)
delete = Button(root, text="Delete", font=("italic", 10), bg="white", command=delete)
delete.place(x=100, y=390)
update = Button(root, text="Update", font=("italic", 10), bg="white", command=update)
update.place(x=160, y=390)
get = Button(root, text="Get", font=("italic", 10), bg="white", command=get)
get.place(x=225, y=390)
list = Listbox(root)
list.place(x=360, y=250)
student = Label(root, text='Student', font=('bold', 15))
student.place(x=130, y=470);
id = Label(root, text='Enter ID', font=('bold', 10))
id.place(x=20, y=510);
name = Label(root, text='Enter Name', font=('bold', 10))
name.place(x=20, y=540);
address = Label(root, text='Enter Address', font=('bold', 10))
address.place(x=20, y=570);
e_id = Entry()
e_id.place(x=150, y=510)
e_name = Entry()
e_name.place(x=150, y=540)
e_address = Entry()
e_address.place(x=150, y=570)
insert = Button(root, text="Insert", font=("italic", 10), bg="white", command=insert)
insert.place(x=40, y=610)
delete = Button(root, text="Delete", font=("italic", 10), bg="white", command=delete)
delete.place(x=100, y=610)
update = Button(root, text="Update", font=("italic", 10), bg="white", command=update)
update.place(x=160, y=610)
get = Button(root, text="Get", font=("italic", 10), bg="white", command=get)
get.place(x=225, y=610)
list = Listbox(root)
list.place(x=360, y=470)
show()
root.mainloop()
How do I separate the 4 buttons for each table? Totally there are 12 buttons in my Python GUI (insert, delete, update, get)*3
What python command should I use? Thank you!
Ive tried to fix most of the issues I found with the code, but at first lets focus around your main problem. The ideal way would be to use would be a Combobox like:
from tkinter import ttk
from tkinter import messagebox
.....
choices = ['Choose a table','faculty','student'] #list of options to be showed
combo = ttk.Combobox(root,values=choices,state='readonly') #declaring a combobox
combo.current(0) #setting the default value to first item in the list.
combo.pack()
buttoninsert = Button(root,text='Insert',command=insertdb)
buttoninsert.pack()
Note that here, you only need 1 button for each function.
Then define insertdb() as:
def insertdb():
if combo.get() == 'Choose a table':
messagebox.showerror('Choose!','Choose an option!')
elif combo.get() == 'faculty':
fid = e_fid.get()
fname = e_fname.get()
fsalary = e_fsalary.get()
if fid=="" or fsalary=="" or fname=="":
messagebox.showinfo("Insert status", "All fields are required")
else:
con = mysql.connect(host="localhost", user="root", password="", database="test0910")
cursor = con.cursor()
cursor.execute("insert into faculty values(%s,%s,%s)",(fid,fname,fsalary))
cursor.execute("commit")
e_fid.delete(0, 'end')
e_fname.delete(0, 'end')
e_fsalary.delete(0, 'end')
show()
messageBox.showinfo("Insert Status", "Inserted Successfully");
con.close()
elif combo.get() == 'student':
id = e_id.get()
name = e_name.get();
address = e_address.get();
if id=="" or name=="" or address=="":
messageBox.showinfo("Insert status", "All fields are required")
else:
con = mysql.connect(host="localhost", user="root", password="", database="test0910")
cursor = con.cursor()
cursor.execute("insert into student values(%s,%s,%s)",(id,name,address))
cursor.execute("commit");
e_id.delete(0, 'end')
e_name.delete(0, 'end')
e_address.delete(0, 'end')
show()
messageBox.showinfo("Insert Status", "Inserted Successfully");
con.close()
So I hope you got a basic idea of whats happening. If not, Its like the user should choose an option at first, and then click on the button, only then the rest of the operation take place. Make necessary changes to the code, so that it fits to your needs.
Similarly, go on defining 3 other buttons and 3 functions, for your purpose.
What all have I changed?
You used concatenation for inserting data to the database and hence it is not a safe way and is exposed to sql injections. So i changed those to parametric substituions. Where you use %s as a placeholder. Take a look here for better understanding of these
I noticed that you named functions as insert(),get() and all. Naming as such is not accurate as some tkinter widgets has insert() and delete() methods, so it might cause a confusion to python later on.
Avoid naming variables as list, id as these are inbuilt functions and it will cause a confusion later on, again.
Ive imported messagebox, while i noticed you used Messagebox. Im not sure if tkinter.Messagebox exists and it might throw an error, if not, its fine to use.
You can add more mysql table names to the list choices and it will appear as options on the Combobox. Check out more on Combobox
Why did I say from tkinter import ttk? It is because Combobox is a ttk widget rather than a direct tkinter widget, which means it has a theme applied to it(looks modern).
I tried to explain this as simple as possible, hopefully you get a perfect idea on how to proceed. Do let me know if any errors, or doubts.
Cheers
I created a program which should dump the username and password in json file
But i am having problem in solving it
plz help
def createAccount():
A = tk.StringVar()
B = tk.StringVar()
root1 = Tk()
root1.resizable(0, 0)
root1.title('Signup')
instruction = Label(root1, text='Please Enter new Credentials')
instruction.grid(row=0, column=0, sticky=E)
nameL = Label(root1, text='New Username: ')
pwordL = Label(root1, text='New Password: ')
nameL.grid(row=1, column=0, sticky=W)
pwordL.grid(row=2, column=0, sticky=W)
nameE = Entry(root1, textvariable=A)
pwordE = Entry(root1, textvariable=B )
nameE.grid(row=1, column=1)
pwordE.grid(row=2, column=1)
signupButton = Button(root1, text='Signup')
signupButton.grid(columnspan=2, sticky=W)
root1.mainloop()
username = A
password = B
with open('user_accounts.json', 'r+') as user_accounts:
users = json.load(user_accounts)
if username in users.keys():
print('error')
else:
users[username] = [password, "PLAYER"]
user_accounts.seek(0)
json.dump(users, user_accounts)
user_accounts.truncate()
print("success")
I tried to convert username and password into string by using tk.StringVar()
But a error is displayed
Plz provide any appropriate solution
tkinter labels don't use normal Python variables types. Instead, they use tcl types, such as StringVar. to get the values of such variables, you can call their .get() method, which returns a native Python value. Now you can convert, change and use it as you like :)