简体   繁体   中英

How to add a button permanently in tkinter?

Is there a way in python tkinter to, when you add a button to a page, to do it permanently even when you stop and run the program again? Like if u were to add the button to a database. I don't know if there's a way to put the widget in a sql table...

You cannot store tkinter objects in a database. The solution is to add information to a file or database that allows you to recreate the buttons when you start the application. For example, you can save the button label to a row in the database, and at startup read the rows and create a button for each row.

Here's a complete program that illustrates the process. Notice that each time you create a button the text is retrieved from the entry widget and it is added to the database. At startup the code will query the database and recreate the buttons.

import tkinter as tk
import sqlite3

def init_db():
    global db
    db = sqlite3.connect("buttons.sqlite")
    cursor = db.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS buttons (id INTEGER PRIMARY KEY AUTOINCREMENT, label VARCHAR)")

def add_button():
    button_text = entry.get() or "Button"
    entry.delete(0, "end")

    create_button(button_text)
    save_button(button_text)

def save_button(button_text):
    cursor = db.cursor()
    cursor.execute("INSERT INTO buttons(label) VALUES(?)", (button_text,))
    db.commit()

def create_button(button_text):
    button = tk.Button(root, text=button_text)
    button.pack(side="top")

def restore_buttons():
    cursor = db.cursor()
    cursor.execute("SELECT id, label from buttons")
    for (row_id, button_text) in cursor.fetchall():
        create_button(button_text)

root = tk.Tk()
toolbar = tk.Frame(root)
toolbar.pack(side="bottom", fill="x")

button = tk.Button(toolbar, text="Add Button", command=add_button)
entry = tk.Entry(toolbar)

entry.pack(side="left")
button.pack(side="left")

init_db()
restore_buttons()

root.mainloop()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM