I'm attempting to create a function that will create a button named after a variable every time the submit to database function is used (1 button for every dataset submitted to my database). Currently I can get the button to name itself, but I'm having trouble offsetting the line for each time it's used. I could just add a simple counter and set row=n, but at this point I'm not sure my approach to the problem is the best. For every dataset there needs to be a button generated for it. Would it be best to approach this by trying to run a program that makes buttons based on my dataset (not exactly sure how I'd do this) or by having my submit return a button with row=counter? Or is there another solution I haven't thought of?
**Note: Looking back on this my buttons don't stay after the program restarts which makes sense. If I'm going to use the submit/counter solution I'll also have to make the data store itself in the code.
**Minimal reproducible code:
from tkinter import *
root = Tk()
root.title('Button')
root.geometry('400x400')
f_name = Entry(root, width=30)
f_name.grid(row=0, column=1)
f_name_lbl = Label(root, text="First Name:")
f_name_lbl.grid(row=0, column=0)
def gen_button():
auto_button = Button(root, text=f_name.get())
auto_button.grid(row=2, column=0, columnspan=2)
submit_btn = Button(root, text="Submit:", command=gen_button).grid(row=1, column=0, columnspan=2, ipadx=100)
I believe I did that right, I apologize I'm new to python and stack overflow
CodePudding user response:
If you do not specify a row, grid
will automatically pick the next row after the last occupied row.
auto_button.grid(column=0, columnspan=2)
Though, if you create a separate frame for these buttons you can use pack
which is a bit easier since pack
aligns widgets along a side. In your case you want them aligned to the top of the frame, just below any other widgets.
def gen_button():
auto_button = Button(button_frame, text=f_name.get())
auto_button.pack(side="top")
submit_btn = Button(root, text="Submit:", command=gen_button)
submit_btn.grid(row=1, column=0, columnspan=2, ipadx=100)
button_frame = Frame(root)
button_frame.grid(row=2, column=0, columnspan=2, sticky="nsew")