Python Forum
Cant transfer a variable onto another function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cant transfer a variable onto another function
#1
The error is in line 17

import tkinter as tk
from tkinter.ttk import *
window = tk.Tk()

def Adder():
    AddingWindow = tk.Toplevel(window)
    AddingWindow.geometry("400x400")
    Label(AddingWindow, text="Mail/Username", width="20", font="Calibri 22 bold").pack()
    name = Entry(AddingWindow, width=50)
    name.pack()
    Label(AddingWindow, text="Password", width="20", font="Calibri 22 bold").pack()
    passw = Entry(AddingWindow, width=50)
    passw.pack()
    Add = Button(AddingWindow, text="Add", width="20").pack()
    
def Save():
   Password = passw.get()
    print(Password)

window.geometry("500x500")
greeting = tk.Label(text="Password Manager: Developed by KEIKAS", font="Calibri 20 bold")
AddB = tk.Button(text="Add", width="20",height="2",bg="green", command=Adder)
AccessB = tk.Button(text="Access", width="20",height="2",bg="blue")
RemoveB = tk.Button(text="Remove", width="20",height="2",bg="red")

greeting.pack()
AddB.pack()
RemoveB.pack()
AccessB.pack()
window.mainloop()
Error:
NameError: name 'passw' is not defined
Reply
#2
One way to get around that would be to uselambdato sendpssw.get ()toSaveas an argument. See if this helps.
import tkinter as tk
from tkinter.ttk import *
window = tk.Tk()
 
def Adder():
    AddingWindow = tk.Toplevel(window)
    AddingWindow.geometry("400x400")
    Label(AddingWindow, text="Mail/Username", width="20", font="Calibri 22 bold").pack()
    name = Entry(AddingWindow, width=50)
    name.pack()
    Label(AddingWindow, text="Password", width="20", font="Calibri 22 bold").pack()
    passw = Entry(AddingWindow, width=50)
    passw.pack()
    Add = Button(AddingWindow, text="Add", width="20")
    Add.config (command = lambda : Save (passw.get()))
    Add.pack ()
 
def Save(Password):
   print(Password)
 
window.geometry("500x500")
greeting = tk.Label(text="Password Manager: Developed by KEIKAS", font="Calibri 20 bold")
AddB = tk.Button(text="Add", width="20",height="2",bg="green", command=Adder)
AccessB = tk.Button(text="Access", width="20",height="2",bg="blue")
RemoveB = tk.Button(text="Remove", width="20",height="2",bg="red")
 
greeting.pack()
AddB.pack()
RemoveB.pack()
AccessB.pack()
window.mainloop()
Reply
#3
Thanks, you helped me out a lot man (:
Reply
#4
You are welcome. I'm happy to help.
Reply
#5
You can also use functools partial to pas variables.

import tkinter as tk
from tkinter.ttk import *
from functools import partial
window = tk.Tk()

def Adder():
    AddingWindow = tk.Toplevel(window)
    AddingWindow.geometry("400x400")
    Label(AddingWindow, text="Mail/Username", width="20", font="Calibri 22 bold").pack()
    name = Entry(AddingWindow, width=50)
    name.pack()
    Label(AddingWindow, text="Password", width="20", font="Calibri 22 bold").pack()
    passw = Entry(AddingWindow, width=50)
    passw.pack()
    Add = Button(AddingWindow, text="Add", width="20")
    Add.config (command = partial(Save, passw))
    Add.pack ()

def Save(Password):
   print(Password.get())

window.geometry("500x500")
greeting = tk.Label(text="Password Manager: Developed by KEIKAS", font="Calibri 20 bold")
AddB = tk.Button(text="Add", width="20",height="2",bg="green", command=Adder)
AccessB = tk.Button(text="Access", width="20",height="2",bg="blue")
RemoveB = tk.Button(text="Remove", width="20",height="2",bg="red")

greeting.pack()
AddB.pack()
RemoveB.pack()
AccessB.pack()
window.mainloop()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#6
Writing GUI code using functions gets messy quick. You should start using classes. Classes do a better job at isolating all the pieces so you don't end up with the kinds of problems you are seeing. This code creates a password dialog class that your application could use for entering a password.
import tkinter as tk
from tkinter.simpledialog import Dialog
from tkinter import messagebox

class PasswordDialog(Dialog):
    """A custom dialog for entering username and password"""
    def __init__(
            self,
            parent=None,
            title="Password",
            user_prompt="User",
            password_prompt="Password",
            user=None,
            validator=None,
            **kwargs):
        self.result = None
        self.user_prompt = user_prompt
        self.password_prompt = password_prompt
        self.user = user
        self.validator = validator
        super().__init__(parent, title, **kwargs)

    def body(self, frame):
        """Place controls in the body of the dialog."""
        tk.Label(frame, text=self.user_prompt).grid(row=0, column=0, padx=5, pady=5, sticky="W")
        self.username = tk.Entry(frame, width=20)
        self.username.grid(row=0, column=1, sticky="EW")
        tk.Label(frame, text=self.password_prompt).grid(row=1, column=0, padx=5, sticky="W")
        self.password = tk.Entry(frame, show="*")
        self.password.grid(row=1, column=1, sticky="EW")

        if self.user is None:
            # Give focus to username
            self.username.select_range(0, tk.END)
            return self.username
        else:
            # Set username and disable.  Give focus to password
            self.username.insert(0, self.user)
            self.username.config(state=tk.DISABLED)
            self.password.select_range(0, tk.END)
            return self.password

    def validate(self):
        """Called when OK button is pressed"""
        if self.validator is not None:
            try:
                self.validator(self.password.get())
            except ValueError as msg:
                messagebox.showwarning("Invalid Password", msg, parent=self)
                return 0
        self.result = (self.username.get(), self.password.get())
        return 1


def askpassword(**kwargs):
    """Draw password dialog.  Return username and password"""
    def validator(pwd):
        """Rules for a valid password"""
        if len(pwd) < 7:
            raise ValueError("Password must contain at least 7 characters")

    return PasswordDialog(root, validator=validator, **kwargs).result


root = tk.Tk()
tk.Button(root, text="New User", command=lambda:print(askpassword())).pack(padx=5, pady=5)
tk.Button(root, text="Clark Kent", command=lambda:print(askpassword(user="Clark Kent"))).pack(padx=5, pady=5)
root.mainloop()
The tkinter Dialog class which I didn't have to write does most of the work.

The PasswordDialog class makes a Dialog with username and password entries. It is easy to customize for you need. You can specify the label text as arguments. You can set the username which disables editing the username. You can specify a function to validate the password.

The askpassword() convenience function draws the password dialog and returns the username and password. It also provides a validator the PasswordDialog can use to validate the entered password.

Each of these pieces is short and self contained, mostly because each piece has one job it has to do. Because each piece does one thing it can have a well defined interface. Because each piece has a well defined interface it is not only easy to write code that uses the pieces, but it is easy to modify the pieces because the changes are hidden by the interface. PasswordDialog doesn't need to know that something internal to Dialog changed because it only uses the published API for dialog. askpassword() doesn't care about changes to Dialog or PasswordDialog as long as they don't change the interface.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable for the value element in the index function?? Learner1 8 667 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 598 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 1,326 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  Function parameter not writing to variable Karp 5 949 Aug-07-2023, 05:58 PM
Last Post: Karp
  Transfer function victoriomariani 0 605 Dec-10-2022, 01:39 PM
Last Post: victoriomariani
  Retrieve variable from function labgoggles 2 1,056 Jul-01-2022, 07:23 PM
Last Post: labgoggles
Information Estimating transfer function from frd data ymohammadi 0 1,452 Feb-10-2022, 10:00 AM
Last Post: ymohammadi
  Transfer function tanh(Tes) swagata 2 1,694 Aug-20-2021, 01:14 AM
Last Post: swagata
  Please explain uncommon way of declaring and using variable [function.variable] esphi 4 2,343 Nov-07-2020, 08:59 AM
Last Post: buran
  Spyder Quirk? global variable does not increment when function called in console rrace001 1 2,237 Sep-18-2020, 02:50 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020