I am trying to display the data from a file and a button and then once the button is clicked, display the new data from a new file along with a button. You can see my print statements in my attempt to debug this. When I run the program, there is output, and it correctly displays a # and a button. However, the # that is displayed is from the last file I have (file #3) instead of from file #1. I believe that file #1 was covered by file #2 which then got covered by file #3. All of this happened without any button being clicked. How can I make the program wait until the button is clicked before displaying the new # and button?
window = Tk()
def clicked():
top = Toplevel(window)
top.geometry('300x300')
popLabel = Label(top, text = "E")
popLabel.place(relx = 0.5, rely = 0.5, anchor = 'center')
for widgets in frame1.winfo_children():
widgets.destroy()
for x in range(1,4):
fileName = "file" + str(x) + ".json"
print(fileName)
frame1 = LabelFrame(window, width = 300, height = 300, padx=10,pady=5)
frame1.grid(row= 0,column=0)
with open(fileName) as f:
data = json.load(f)
#print(data)
num = "#" + data.get("id")
print(num)
numLabel = Label(
frame1,
text = num
).grid(row = 1, column = 1)
firstButton = Button(
frame1,
text = "A",
command = clicked
).grid(row = 2, column = 1, sticky = 's')
window.mainloop()
I guess your real problem was that you overwrite the frame every time in the loop. So define your frame before the loop and set the column number as a variable.
import tkinter as tk
window = tk.Tk()
def clicked(number):
top = tk.Toplevel(window)
top.geometry('300x300')
fileName = "file" + str(number)+ ".json"
# with open(fileName) as f:
# data = json.load(f)
data = "data"
num = "#" # data.get("id")
popLabel = tk.Label(top, text = fileName)
popLabel.place(relx = 0.5, rely = 0.5, anchor = 'center')
#for widgets in frame1.winfo_children():
# widgets.destroy()
frame1 = tk.LabelFrame(window, width = 300, height = 300, padx=10,pady=5)
frame1.place(relwidth = 1, relheight= 1)
for x in range(1,4):
num = "#"
numLabel = tk.Label(
frame1,
text = num
).grid(row = 1, column = x)
firstButton = tk.Button(
frame1,
text = "A_{}".format(x),
command= lambda x =x: clicked(x)
).grid(row = 2, column = x, sticky = 's')
window.mainloop()
EDIT: In this case, I would put the open
command in the checked
function and tell them the number of parameters to load.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.