Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python tkinter保存外观更改_Python_Tkinter - Fatal编程技术网

Python tkinter保存外观更改

Python tkinter保存外观更改,python,tkinter,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() 要保存/恢复外观,您需要保存按钮的数量。基本思想是: 读取包含按钮数量的配置文件并创

如何使两个按钮在关闭程序并调用函数后仍然出现,从而导致添加更多按钮? 代码如下:

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

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

  • 读取包含按钮数量的配置文件并创建它们(请参见下面代码中的
    restore\u window()
  • 让用户添加任意数量的按钮,跟踪添加了多少按钮(在
    number\u of_btn
    变量中)
  • 关闭窗口时,在文件中保存按钮数。为此,我使用了
    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()
    
    

    您需要保存按钮的数量,例如,在关闭时保存在文件中,并在启动应用程序时读取文件以还原GUI。您可以通过示例显示,因为我是初学者,不知道如何使新创建的按钮具有不同的文本、命令、位置?@marcin您可以使用(文本、命令、位置)列表对于您的按钮,如果需要,甚至可以在列表中随机选择。如果您需要保存一个更复杂的GUI,您可能希望使用一些不仅仅是文本文件的东西,例如,使用配置文件或使用保存词汇表。如果您在探索这些选项时有更多问题,请提出新的问题。