Get the same input multiple times in python tkinter?
Behavior of your program is a bit unclear for me, but I try to help.
First solution: show tkinter askstring dialog num
times. You can break for
loop if user press Cancel
button. It's not exactly what you want, but it's very easy to implement:
from tkinter import *import tkinter.simpledialog as simpledialogdef add_users(): n = simpledialog.askinteger('', 'How many users are you going to put in?', initialvalue=1, minvalue=1, maxvalue=10) if not n: # 'Cancel' return for i in range(n): user = simpledialog.askstring('', 'User #%s from #%s' % (i+1, n)) if user is None: # 'Cancel' return # Do something useful print(user)root = Tk()Button(root, text='Add users', command=add_users).pack(padx=50, pady=50)Button(root, text='Quit', command=root.destroy).pack(pady=30)root.mainloop()
Second (if you want to put entry and all new names to window with quit
button):
from tkinter import *import tkinter.simpledialog as simpledialogclass YourApp(): def __init__(self): self.root = Tk() Button(self.root, text='Quit', command=self.root.destroy).pack(pady=20) self.ask_button = Button(self.root, text='Add users', command=self.add_users) self.ask_button.pack(padx=50, pady=50) self.root.mainloop() def add_users(self): self.users_count = 0 self.user_name = StringVar() self.frame = Frame(self.root) self.frame.pack() self.users_count = simpledialog.askinteger('', 'How many users are you going to put in?', initialvalue=1, minvalue=1, maxvalue=10) self.user_entry = Entry(self.frame, textvariable=self.user_name) self.user_entry.pack(pady=10) self.user_entry.bind('<Key-Return>', self.on_new_user) self.user_entry.focus_set() def on_new_user(self, event): # your code print(self.user_name.get()) Label(self.frame, text='User Inputted: %s' % self.user_name.get()).pack() self.users_count -= 1 if not self.users_count: self.user_entry.destroy() self.user_name.set('')YourApp()
There are three geometry managers in Tkinter: place (it's very similar to canvas in your case), grid and pack.Canvas usually used for drawing pictures or graphs.