On another project, I have a bunch of labels that gets updated whenever a list of strings is given. But if I wanted to add a string to this list and show that with the labels, I would have to destroy and remake all of them again. To simplify it, the below code is my starting point.
from tkinter import *
root = Tk()
a = Label(root, text ="Hello World")
a.pack()
b = Label(root, text = "Goodbye World")
b.pack()
# third label to add between label A and B
root.mainloop()
Is there some kind of insert function or other way to solve this?
EDIT: answer from Bryan Oakley:
Should use the before/after parameter in pack of label
# third label to add between label A and B
c = Label(root, text="Live long and prosper")
c.pack(before=b)
CodePudding user response:
The order in which you call pack
matters, in that it establishes the order in which the widgets appear relative to each other. pack
also provides arguments to change that order. You can specify before
to add a widget before another widget, and after
to place the widget after.
This code places the third label before widget b
:
# third label to add between label A and B
c = Label(root, text="Live long and prosper")
c.pack(before=b)
This code places the third label after widget a
:
# third label to add between label A and B
c = Label(root, text="Live long and prosper")
c.pack(after=a)
CodePudding user response:
I'm not entirely sure that this is what you meant with your question but if you want to insert a third label between Label1 and Label2 (a, b) just insert it manualy.
from tkinter import *
root = Tk()
a = Label(root, text="Hello World")
a.pack()
# third label to add between label A and B
c = Label(root, text="Middle Label")
c.pack()
b = Label(root, text="Goodbye World")
b.pack()
root.mainloop()
this way it's gonna show on the screen between a and b. and if you want to insert new text to an already existing Label you can just use the .configure() method to change the text of a specific Label whenever you want, like this:
from tkinter import *
lst = ["Oof"]
root = Tk()
a = Label(root, text="Hello World")
a.pack()
# third label to add between label A and B
c = Label(root, text="Middle Label")
c.pack()
b = Label(root, text="Goodbye World")
b.pack()
# Here I will add a simple code that asks the user to enter a number
# between one and ten, if it's between those numbers then change the
# text to "Nice Choice!" else to first element of the list called lst
guess = int(input("Enter a number (1 - 10): "))
if 1 <= guess <= 10:
c.configure(text="Nice choice!")
else:
c.configure(text=f"{lst[0]}") # Using f string
root.mainloop()