Не могу уничтожить кнопки ткинтер - PullRequest
0 голосов
/ 22 апреля 2020

У меня есть этот код:

from tkinter import *

root = Tk()
root = root
root.title("1")
root.geometry('600x650')

def click():
   b.destroy()
b = (1, 2, 3, 4, 5)
for i in b:
   b = Button(root, text=i, command=click)
   b.pack()

print("success")

root.mainloop()

Мне нужна кнопка уничтожения, которую я нажал, но она уничтожает последнюю сгенерированную кнопку.

Пожалуйста, не советуйте код, подобный этому:

from tkinter import *

root = Tk()
root = root
root.title("1")
root.geometry('600x650')

def click1():
    button1.destroy()
def click2():
    button2.destroy()

button1 = Button(root, text="1", command=click1)
button2 = Button(root, text="2", command=click2)
button1.pack()
button2.pack()

print("success")

root.mainloop()

Мне нужно, чтобы каждая кнопка могла закрываться сама.

Ответы [ 3 ]

1 голос
/ 22 апреля 2020

Вот пример того, что я имел в виду в своем комментарии.

from tkinter import *
from functools import partial

root = Tk()
root = root
root.title("1")
root.geometry('600x650')

# specify which button to click
def click(index):
    buttons[index].destroy()

b = (1, 2, 3, 4, 5)
# keeping our buttons in a list allows us to destroy them individually
buttons = []
for index, i in enumerate(b):
    # use functools.partial to hand arguments to the callback function
    # the argument being the button you are clicking  
    buttons.append(Button(root, text=i, command=partial(click, index)))
    buttons[index].pack()

print("success")

root.mainloop()

Вот ваш пример, который вы привели, и где он терпит неудачу.

from tkinter import *

root = Tk()
root = root
root.title("1")
root.geometry('600x650')

# the function destroys b
# that b is the last button you created in your loop below
def click():
   b.destroy()

# you create a tuple of numbers and assign it to b
b = (1, 2, 3, 4, 5)
for i in b:
   # for every loop a button is created and packed and assigned to b
   # but that is overwritten on every subsequent loop 
   # since you keep assigning to b
   b = Button(root, text=i, command=click)
   b.pack()

print("success")

root.mainloop()
0 голосов
/ 22 апреля 2020

Вы можете попробовать это

from tkinter import *

root = Tk()
root = root
root.title("1")
root.geometry('600x650')
bts = [1, 2, 3, 4, 5]

f = Frame(root)
f.pack()

def click(val):
    global bts, root, b, f

    f.destroy()
    f = Frame(root)
    f.pack()

    bts.remove(val)
    for i in bts:
        b = Button(f, text=i, command=lambda x=i: click(x))
        b.grid(row=int(i - 1), column=1)


for i in bts:
   b = Button(f, text=i, command=lambda x=i: click(x))
   b.grid(row=int(i-1), column=0)

print("success")

root.mainloop()
0 голосов
/ 22 апреля 2020

В этом разделе вы определяете кортеж как b, затем перезаписываете b в каждой итерации:

b = (1, 2, 3, 4, 5)
for i in b:
   b = Button(root, text=i, command=click)
   b.pack()

Но главная проблема в том, что в b всегда есть только 1 кнопка, Вы хотите, чтобы каждая кнопка была сохранена в list, например:

from tkinter import *

root = Tk()
root = root
root.title("1")
root.geometry('600x650')

def click(idx):
    # Here x is used to determine the button's location in list b.
    b[idx].destroy()

buttons = (1, 2, 3, 4, 5)
b = [] # Make b a list.
for x, i in enumerate(buttons):
    b.append(Button(root, text=i,
                    # Here lambda stores x for each iteration, and assigns it to click.
                    command= lambda idx = x: click(idx)))
    b[-1].pack() # Pack the last button appended to b.

print("success")

root.mainloop()

По сути, то же самое, используя лямбду, но я уже набрал ее, поэтому я публикую ее.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...