因此,我正在使用Python进行交互式元素周期表项目,并且正在使用Tkinter。我上面有一些按钮,单击这些按钮可提供有关在按钮上命名的元素的信息。它将其输出为标签,并在5.5秒后自动消失。我需要做一件事,但似乎找不到以下解决方案:
我需要进行设置,以便一次只能显示一个标签。当前,如果我多次单击相同或不同的按钮,则标签会相互堆叠。我只希望有一个标签,所以如果单击一个新按钮,则该标签将替换另一个标签。
这是主要代码,其中包含所有Tkinter内容。我还将在底部包含我使用所有元素周期表库内容制作的另一个文件。
from elementsymbols import *
from tkinter import *
def callback_h():
labelh = Label(root, text="Element name: " + str(h.name) + "\n" + "Element symbol: " + str(h.symbol) + "\n" + "Atomic mass: " + str(h.atomic_weight) + "\n" + "Atomic number: " + str(h.atomic_number))
labelh.pack()
labelh.after(5500, lambda: labelh.config(text=''))
def callback_he():
labelhe = Label(root, text="Element name: " + str(he.name) + "\n" + "Element symbol: " + str(he.symbol) + "\n" + "Atomic mass: " + str(he.atomic_weight) + "\n" + "Atomic number: " + str(he.atomic_number))
labelhe.pack()
labelhe.after(5500, lambda: labelhe.config(text=''))
def callback_li():
labelli = Label(root, text="Element name: " + str(li.name) + "\n" + "Element symbol: " + str(li.symbol) + "\n" + "Atomic mass: " + str(li.atomic_weight) + "\n" + "Atomic number: " + str(li.atomic_number))
labelli.pack()
labelli.after(5500, lambda: labelli.config(text=''))
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
# Creation of init_window
def init_window(self):
# changing the title of our master widget
self.master.title("Interactive Periodic Table v1")
# allowing the widget to take the full space of the root window
self.pack(fill=BOTH, expand=1)
# creating a button instance
hbutton = Button(self, text="Hydrogen - H", command=callback_h)
# placing the button on my window
hbutton.place(x=0, y=0)
# all other elements
hebutton = Button(self, text="Helium - He", command=callback_he)
hebutton.place(x=100, y=0)
libutton = Button(self, text="Lithium - Li", command=callback_li)
libutton.place(x=190, y=0)
root = Tk()
# size of the window
root.geometry("600x500")
app = Window(root)
root.mainloop()
这是主要代码,这是从中获取周期表信息的位置:
from mendeleev import element
h = element('H')
he = element('He')
li = element('Li')
be = element('Be')
b = element('B')
c = element('C')
n = element('N')
o = element('O')
f = element('F')
ne = element('Ne')
na = element('Na')
mg = element('Mg')
al = element('Al')
si = element('Si')
p = element('P')
s = element('S')
cl = element('Cl')
ar = element('Ar')
k = element('K')
ca = element('Ca')
sc = element('Sc')
ti = element('Ti')
v = element('V')
cr = element('Cr')
任何与此有关的帮助,将不胜感激,但是与我的代码有关的实际代码示例将非常有帮助,非常感谢。
您可以在列表中保留标签的引用,然后在回调期间仅遍历它们,并根据需要更改其文本/销毁/隐藏/显示它们。
def callback:
for lbl in my_labels:
# Destroy the previous labels
lbl.destory()
# Or disable it using something like lbl.pack_forget()
# Create new label or whatever
new_label = Label(root... etc, etc.