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
#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


Messages In This Thread
RE: Cant transfer a variable onto another function - by deanhystad - Feb-09-2022, 10:17 PM

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