簡體   English   中英

如何在 tkinter 中永久添加按鈕?

[英]How to add a button permanently in tkinter?

python tkinter 有沒有辦法,當您向頁面添加按鈕時,即使您停止並再次運行程序,也可以永久執行此操作? 就像您要將按鈕添加到數據庫一樣。 我不知道是否有辦法將小部件放入 sql 表中......

您不能將 tkinter 對象存儲在數據庫中。 解決方案是將信息添加到文件或數據庫中,以便您在啟動應用程序時重新創建按鈕。 例如,您可以將按鈕標簽保存到數據庫中的一行,並在啟動時讀取這些行並為每一行創建一個按鈕。

這是一個完整的程序來說明這個過程。 請注意,每次創建按鈕時,都會從條目小部件中檢索文本並將其添加到數據庫中。 在啟動時,代碼將查詢數據庫並重新創建按鈕。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM