python - tkinter: What should I do if I want to delete the number in the order of the button?
问题描述
from tkinter import*
import tkinter as tk
class QueueApp(tk.Tk):
def __init__(self):
super().__init__()
self.title(' Queue')
self.minsize(200, 200)
self.x=0
self.frame1=tk.Frame(self)
self.frame1.place(x=0,y=0,width=70,height=170,anchor='nw')
self.frame2=tk.Frame(self)
self.frame2.place(x=40,y=175,anchor='nw')
self.frame3 = tk.Frame(self)
self.frame3.place(x=100, y=0, width=50, height=170, anchor='nw')
add=tk.Button(self.frame2,text='add',command=self.add_text)
add.pack()
def add_text(self):
self.x=self.x+1
self.text=tk.Label(self.frame1,text=self.x)
self.text.pack(side=tk.TOP)
self.delete_button=tk.Button(self.frame3,text='delete',
command=self.delete)
self.delete_button.pack(side=tk.TOP)
def delete(self):
self.text.destroy()
self.delete_button.destroy()
if __name__=='__main__':
app = QueueApp()
app.mainloop()
i want to delete 2 when I press the second delete button, but it will only delete 4 when the last number is 4. No matter which button I press, it will always delete the last number. What should I do if I want to delete the number in the order of the button?
解决方案
Each time you create a new text widget you do override the previous one. Therefore you can only delete the last created one.
Possible solution: Create button and label widgets and store them in a list.
import tkinter as tk
class QueueApp(tk.Tk):
def __init__(self):
super().__init__()
self.title(' Queue')
self.minsize(200, 200)
self.x = 0
self.frame1=tk.Frame(self)
self.frame1.place(x=0,y=0,width=70,height=170,anchor='nw')
self.frame2=tk.Frame(self)
self.frame2.place(x=40,y=175,anchor='nw')
self.frame3 = tk.Frame(self)
self.frame3.place(x=100, y=0, width=50, height=170, anchor='nw')
add=tk.Button(self.frame2,text='add',command=self.add_text)
add.pack()
#create lists
self.myDeleteButtons = []
self.myTextLabels = []
def add_text(self):
self.button_name = "delete"+str(self.x)
self.text=tk.Label(self.frame1,text=self.x)
self.text.pack(side=tk.TOP)
#lambda: for passing counter variable as argument
self.delete_button=tk.Button(self.frame3,text=self.button_name,
command=lambda x=self.x: self.delete(x))
self.delete_button.pack(side=tk.TOP)
#add widgets in list
self.myDeleteButtons.append(self.delete_button)
self.myTextLabels.append(self.text)
self.x += 1
def delete(self, button_nr):
#use argument as index
self.myDeleteButtons[button_nr].destroy()
self.myTextLabels[button_nr].destroy()
if __name__=='__main__':
app = QueueApp()
app.mainloop()
When you delete all buttons you can set counter variable to zero.
推荐阅读
- next.js - SyntaxError:不能在 nextjs 的模块外使用 import 语句
- php - 每当我在自定义查询中使用 meta_key 时,我都没有得到预期的结果
- angular8 - 如何在 angular 8 mat table 上获取搜索结果计数
- reactjs - 如何使用 AntDesign 将自定义添加按钮添加到水平选项卡
- javascript - javascript文本函数中的粗体字体
- python - 在数据点之间添加箭头
- c++ - 断点不适用于 Visual Studio Code 中的 C++ 应用程序
- java - HIbernate - 尝试获取数据时出现“无法初始化代理 - 无会话”错误
- vuejs3 - 如何避免硬编码数据对象
- excel - Excel - 随机抽样