![](/img/trans.png)
[英]How to delete multiple selected item in a listBox - with Python Tkinter
[英]How to delete from Mysql Database an item selected in a Listbox Python Tkinter
我已經創建了一個包含 3 列(id、名稱、價格)的數據庫,並且由於我無法顯示列表框中的所有列,因此我只顯示列“名稱”,所以我希望能夠刪除列表框中的項目基於我單擊列表框的產品名稱的數據庫。 這是代碼,我希望它有幫助:
import tkinter
from tkinter import *
import mysql.connector
root = Tk()
root.geometry('700x500')
con = mysql.connector.connect(user = '', password = '', host = '127.0.0.1', database = 'anime')
concursor = con.cursor()
concursor.execute('select * from prod')
query = concursor.fetchall()
l = Listbox(root)
for x,y,z in query:
l.insert(x+1, y)
l.pack(anchor='w')
#function to delete prod
def delp():
sel_items = l.curselection()
for item in sel_items:
concursor.execute("delete from prod where name = ('{}')".format(item))
con.commit()
button1 = Button(root, text = 'prod del', command = delp)
button1.pack(anchor='w')
root.mainloop()
python 代碼僅當我在“delp”function 的查詢中將“名稱”替換為“id”時才有效,但是當我在 select 中刪除第 2 項時可以根據名稱刪除。
所以我想通了,所以這就是那些正在/將要尋找這個的人的答案。
首先,我們不需要 curselection() 我們需要獲取活動項目或 Anchor 並“將其串起來”,然后在查詢中使用它的格式。 這是有意義的代碼
def delp():
sel_items = l.get(ACTIVE)
string_item = str(sel_items)
for item in sel_items:
concursor.execute("delete from prod where name = ('{}')".format(string_item))
con.commit()
此代碼將根據列表框中的名稱 select 刪除數據庫中的項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.