gpt4 book ai didi

python - tkinter:如果我想删除按钮顺序中的数字该怎么办?

转载 作者:行者123 更新时间:2023-12-01 08:55:55 29 4
gpt4 key购买 nike

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

我想在按第二个删除按钮时删除2,但是当最后一个数字是4时它只会删除4。无论我按哪个按钮,它总是会删除最后一个数字。如果我想删除按钮顺序中的号码该怎么办?

example

最佳答案

每次创建新的文本小部件时,都会覆盖前一个文本小部件。因此您只能删除最后创建的一个。

可能的解决方案:创建按钮和标签小部件并将它们存储在列表中。

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

当您删除所有按钮时,您可以将计数器变量设置为零。

关于python - tkinter:如果我想删除按钮顺序中的数字该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52769013/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com