节省外观变化

时间:2019-12-27 15:31:15

标签: python tkinter

在关闭程序并调用该函数导致添加更多按钮后,如何使两个按钮仍然显示? 这是代码:

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()

1 个答案:

答案 0 :(得分:0)

要保存/恢复外观,则需要保存按钮数量。基本思想是:

  1. 读取包含按钮数量的配置文件并创建它们(请参见下面的代码中的restore_window())。
  2. 让用户根据需要添加任意数量的按钮,并跟踪添加的按钮数量(在number_of_btns变量中。)
  3. 在关闭窗口时将按钮的数量保存在文件中。为此,我使用了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()