How do you get a different value for a label each time a button is pressed in `tkinter`?
You generate the random name only once. From then on estr
is always going to be the same value.
If you're comfortable with lambda
you can use that to make full_name
into a function:
full_name = lambda: random.choice(firstnameli) + random.choice(lastnameli)
Afterwards, you'll have to call full_name
since it's not a simple string variable anymore but a function:
estr.set(full_name())
Also, you seem to miss setting textvariable=estr
for fullnameentry
.
Everything put together:
firstnameli = ['Chris ', 'Kevin ', 'Jeff ', 'Marty ', 'Dolen ']lastnameli = ['Smith', 'Miller', 'Jones', 'Davis', 'Brown']full_name = lambda: random.choice(firstnameli) + random.choice(lastnameli)#this allows text to be put in the text boxestr = StringVar()estr.set(full_name())fullnameentry = Entry(MyWin, textvariable=estr, borderwidth=5, font=("Helvetica", 15))def buttonfunc(): estr.set(full_name())genbutton = Button(MyWin, text="GENERATE", activebackground="blue", command=buttonfunc)
I also think your code might be a little bit too complicated at some points. Here is a minimal and complete tkinter
example, maybe this will help you in some way:
import tkinter as tkimport randomdef random_name(): first_names = ['Chris', 'Kevin', 'Jeff', 'Marty', 'Dolen'] last_names = ['Smith', 'Miller', 'Jones', 'Davis', 'Brown'] full_name = '{} {}'.format(random.choice(first_names), random.choice(last_names)) return full_namedef update_label_and_entry(): new_random_name = random_name() label.config(text=new_random_name) entry.delete(0, tk.END) # delete content from 0 to end entry.insert(0, new_random_name) # insert new_random_name at position 0root = tk.Tk()label = tk.Label(root)label.pack()entry = tk.Entry(root)entry.pack()button = tk.Button(root, text="New random name", command=update_label_and_entry)button.pack()root.mainloop()
Of course, this code is not perfect. The code could be improved further for example by moving first_names
and last_names
to a global namespace, so other methods can access the values, too. Also, you could write a class for your window or for the label which will include the update_label
method.