在关闭程序并调用该函数导致添加更多按钮后,如何使两个按钮仍然显示? 这是代码:
from tkinter import *
win = Tk()
def add_button():
b2 = Button(win, text="click").grid()
b1 = Button(win, text="click", command=add_button).grid()
win.mainloop()
答案 0 :(得分:0)
要保存/恢复外观,则需要保存按钮数量。基本思想是:
restore_window()
)。number_of_btns
变量中。)win.protocol("WM_DELETE_WINDOW", save_and_close)
在用户关闭窗口时执行save_and_close()
。 这是完整的代码:
# from tkinter import * -> to be avoided because it may lead to naming conflicts
import tkinter as tk
number_of_btns = 0 # keep track of the number of buttons
def restore_window():
try:
with open("window_config.txt", "r") as file: # open file
nb = int(file.read()) # load button number
except Exception: # the file does not exist or does not contain a number
nb = 0
for i in range(nb):
add_button()
def save_and_close():
with open("window_config.txt", "w") as file:
# write number of buttons in file
file.write(str(number_of_btns))
win.destroy()
def add_button():
global number_of_btns # change value of number_of_btns outside the scope of the function
b2 = tk.Button(win, text="click").grid()
number_of_btns += 1
win = tk.Tk()
win.protocol("WM_DELETE_WINDOW", save_and_close) # execute save_and_close when window is closed
b1 = tk.Button(win, text="Add", command=add_button).grid()
restore_window()
win.mainloop()