Home > Enterprise >  How to refresh a label in tkinter by clicking a button?
How to refresh a label in tkinter by clicking a button?

Time:09-29

I am trying to learn python and want to make a password generator with a tkinter display. When I try to use StringVar to generate a password by clicking a button, it doesn't work and the label shows me the same text.

import random as rd 
import string as stg
from tkinter import *


def generatePassword(size):

    min=size
    max=size
    string_format = stg.ascii_letters   stg.digits
    generated_password = "".join(rd.choice(string_format) for x in range(rd.randint(min, max)))

    with open("pwd_logs.txt","a") as f:
        f.write(f"{generated_password}\r")
        f.close()

    string_var.set(generated_password)




color = ""

screen = Tk()
screen.title("Password generator")
screen.config(bg=color)
screen.geometry("200x200")

string_var = StringVar()
generation_b = Button(screen,text="generate", command=generatePassword(15)).pack()
label = Label(screen,text="Password", bg=color, textvariable=string_var).pack()

screen.mainloop()

I also need to configure the label so that the text "password" appears when the program starts instead of the password.

CodePudding user response:

First of all, get rid of the empty color string because it causes problems.

Now, your issue is that the command argument for Tkinter objects requires a function with no inputs. If it is None, there will be no function bound to it. What you actually set to the command argument is the result of generatePassword(15), which is None. Instead, you want to make the following changes:

def generatePassword():
    # this is static anyway
    size = 15
    ...

generation_b = Button(screen, text="generate", command=generatePassword)
generation_b.pack()

If you have any plans of reusing the function with different inputs, but in the case of the button it's 15 characters, then you can use a lambda.

def generatePassword(size):
    ...

generation_b = Button(screen, text="generate", command=lambda: generatePassword(15))
generation_b.pack()

In order to have the word password appear for the label at the beginning, just set the value of string_var so before calling screen.mainloop().

Note: A mistake that many beginners do with Tkinter is chain calls and then save the result of that call (example). Either break up the creation of the object and placing the object itself, or chain the calls in one line if and only if you don't intend to keep a reference to the object.

  • Related