Using a variable from an other class tkinter python - python

I'm using Tkinter (with python) to create a UI. How can I use the entry (which defines the user name) from one page on another page (thus another class)?
Basically, I need the user name to appear on several pages without asking the user to enter it each time.

you can make it a global variable.
global password
password_entry = tk.Entry(screen1, show="*", textvariable=password)
And then use it anywhere in your program

I don't know do you have any database which includes the usernames. If yes you can get it from there.
if not, so you can use global variable to keep username.
global username
username = textbox.get("1.0","end")

Related

My SQL Login Function to Switch Frames Doesn't Work

My login function doesn't accept the correct username and password when inputted.
So, I'm trying to make a book management system using sqlite3 that has a two frames in a Tkinter window, f1 and f2. f1 contains a login function where if the correct username and password from the database are inputted, it moves to another frame using tkinter. However, it always goes for the "else" condition and says the username and password are incorrect.
def Login():
Connect()
Username=StringVar()
Password=StringVar()
cursor.execute("SELECT * FROM Users WHERE username=? and password=?",(Username.get(), Password.get(),))
connection.commit()
users = cursor.fetchall()
print(users)
connection.commit()
if users is True:
f2.pack(fill='both', expand=1)
f1.pack_forget()
else:
label1=Label(root,text="Wrong username or password, please try again")
label1.place(x=350,y=300)
e2.delete(0, END)
It seems that I'm not getting anything back from the database with the SELECT command for some reason. Advice would really be appreciated!
You're calling Username.get() and Password.get() about a millisecond after creating those variables. There's no way for them to have any value than their initial value, which will be an empty string since you don't give them an explicit default value.
Instead of creating the variables in the function, you should call the get methods of an Entry widget, assuming your program uses Entry widgets. Or, whatever code calls Login must also pass in the username and password. It's not clear from your question where you expect those values to come from.

How to pass user input from one script to another in Python?

I'm creating a GUI application using PyQt5 and am struggling with passing a user input retrieved from a QLineEdit in the first script into the second script.
The first script is a log-in page and I am trying to pass the username entered in the line edit box into the main application (which is a separate file) as it needs to be displayed in that interface.
I have researched this and have only come across methods which pass fixed variables such as 'x = 5' (constants) rather than a user input. How would I go about using a variable that could change at runtime? I have tried the
from __main__ import *
method in the called file and I've tried to convert the username variable into a string using 'str(username)' and setting the variable as global but it seems I still get the same error and when the second file is called and it crashes with no error being displayed.
Here is the relevant code taken from different areas of the script:
file1.py
import os
global username
username = self.lineEdit_username.text()
username = str(username)
import file2
MainWindow.close()
os.system('file2.py')
file2.py
from __main__ import *
print(username) # just to check if the variable has been imported
I've tried researching this as much as I can before posting this but if I have missed a solution somwhere else please point me in the right direction.
Thanks for the help
The easiest way I have done this, especially with PyQt, is utilizing classes and importing the file as a module. See the example below.
Pass_variable.py:
import tkinter as tk
class user_input(object):
def get_input(self):
def get_text():
self.entry = user_entry.get()
print(self.entry)
root.destroy()
root = tk.Tk()
root.title('Name')
user_entry = tk.Entry(root)
user_entry.pack()
user_entry.focus_set()
okay_button = tk.Button(root,text='okay',command=get_text)
okay_button.pack(side='bottom')
root.mainloop()
retrieve_variable.py:
from Pass_variable import user_input
x = user_input()
x.get_input()
print(x.entry)
so you are basically importing the class user_input from the file Pass_variable, assigning x to the class and then anything that is under self is now stored in the x variable. So x.entry is the same thing as calling self.entry inside the pass_variable.py file.
Does this make sense?

I have a tkinter entry box in python but I can't get the input from it into my code?

This is my code below :
from tkinter import *
login = Tk()
username_1 = Entry()
username_1.pack(side=TOP)
input_username = login.username_1.get("1.0", END)
username = input_username
loginInfo = {"user1": "blue", "user2": "yellow", "user3": "green"}
if username in loginInfo:
print('Username correct!')
login.mainloop()
This is my error:
'AttributeError: '_tkinter.tkapp' object has no attribute 'username_1'':
When you create widgets, you are creating children of the root window. However, these children are not attributes of the root window. Thus, login.username_1 is invalid, just as the error is telling you.
In this specific case, the widget is simply username_1 (eg: input_username = username_1.get("1.0", END)). However, even that won't work for the following reasons:
the get method of the entry doesn't take arguments. You need to do username_1.get().
you are calling get about one millisecond after the entry has been created, well before the user has a chance to enter anything.
With a GUI toolkit you can't think of your program running linearly from top to bottom. Instead, you set things up to initially appear, and then you need to write functions that respond to events such as key presses and button clicks. For example, you might want to create a button with the label "Login" that calls a function to check for valid credentials. It would be within that function that you call the get() method.
Can you please provide information about what your code is supposed to do?
If you just want to avoid this error - change line 6 for this:
input_username = username_1.get()

How to get a menu checkbutton to call a function in Python + Tkinter?

so, I'm now in a personal project (just to try myself) with python + tkinter. It is a encrypter, which means that it gets a piece of text and encrypts it using some famous cyphers (like the numerical cypher, the caesar's cypher, and others).
Now, I wanted to give the user the option to save the text he encrypted, and also the encrypted text generated by the program. For that, I created two checkbutton on the program's menu: one for "save text" and the other for "save encrypted text". My question is, I tried to attach a function as it's command option, so, I guess it should run that function when the option is clicked. But it isn't happening.
I'll just explain what the funcitions shouls do before passing the code.
They should prompt a question, asking the user if he/she really wants to create a text file with the text and the encrypted text (This isn't a database, it's just something for the user to be able to read later the text's he/she encrypted and the encrypted version, if he/she wants to).
So, to the code:
encryptermenu = Menu(menubar, tearoff=0)
encryptermenu.add_checkbutton(label="Save Text", variable=v, command=saveText)
encryptermenu.add_checkbutton(label="Save Encrypted Text", variable=w, command=saveEncryptedText)
menubar.add_cascade(label="Encrypter", menu=encryptermenu)
The checkbutton options, and now the functions:
def saveText():
sdtst = messagebox.askyesno(title="Save Text", message="A .txt file will be created at the same directory as this program to save the text you decided to encrypt. Is it ok?")
def saveEncryptedText():
sdtset = messagebox.askyesno(title="Save Encrypted Text", message="A .txt file will be created at the same directory as this program to save the encrypted text generated by this program. Is it ok?")
Should the checkbutton really run the function on-click or am I just making confusion?
Anyway, hope someone will help me.
Checkbutton Menu can definitely call a function. That is what the checkbutton option is there for :)
I generally use 2 functions to handle a call from the checkbutton menu.
first create that menu and assign it to a boolean var
yesno = BooleanVar(root)
mymenu.add_checkbutton(label="Do this ?", variable=yesno, command=mytoggle)
then you need 2 functions:
1) one callback to toggle
2) one to handle yes
def mytoggle(event=None):
val = yesno.get()
if val:
dosomething()
else:
somethingelse()
To answer your specific question, yes, the function will be called when you click on the checkbutton.
You should be calling add_command rather than add_checkbutton on the menu. Using a checkbutton to call a function from a menu is highly unusual and will likely confuse your users.

How can I get user's choice using Tkinter.StringVar?

I am writing a GUI code using Tkinter in python:
var_alg_name = Tk.StringVar(board, 'Bilinear')
Tk.Label(board, text = 'Algorithm Name: ').pack(side = 'left')
ttk.Combobox(board, textvariable = var_alg_name, values=['Bilinear', 'Idw']).pack(side = 'left')
I want to get use's choice when a user choose a option in the list.
By searching help command, I found .trace to call a callback foo, but how can I get the value inside foo?
You simply call var_alg_name.get(), assuming that var_alg_name is accessible in the scope where you're trying to get the value. See Set a default value for a ttk Combobox for an example.

Categories