我正在处理一个应用程序,并且遇到了一些困难。我希望将字典中的键作为标签,列表中的四个数字是相应键的值,并显示在按钮中。当我按下一个按钮时,我想更改标签和按钮,以便它转到字典中的下一个元素并继续重复该过程,直到字典中没有更多元素。
到目前为止,这是我的代码:
import tkinter as tk
q_a = {"label":[1,2,3,4],"label 2":[5,6,7,8]}
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.label = tk.Label(self)
self.label.pack()
self.remaining = len(q_a)
self.countdown(self.remaining-1)
def loop(self, remaining=None):
if self.remaining <= 0:
self.label.configure(text="The end")
else:
self.label.configure(text=(list(q_a.keys())[self.remaining-1]))
dictionary_index = list(q_a.keys())[self.remaining-1]
self.remaining = self.remaining - 1
button1 = tk.Button(self, text=q_a[dictionary_index][0],
command=lambda: self.loop).pack()
button2 = tk.Button(self, text=q_a[dictionary_index][1],
command=lambda: self.loop).pack()
button3 = tk.Button(self, text=q_a[dictionary_index][2],
command=lambda: self.loop).pack()
button4 = tk.Button(self, text=q_a[dictionary_index][3],
command=lambda: self.loop).pack()
if __name__ == "__main__":
app = ExampleApp()
app.mainloop()
答案 0 :(得分:0)
首先我创建空标签和按钮,然后我使用override func layoutSubviews() {
// self.frame.size.width = 300
//self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: 200, height: self.frame.height)
}
仅更改标签和按钮上的文字。
我使用list而不是dictionary loop
来控制列表中哪些数据我必须用作文本。
self.current
BTW:最终你可以将按钮保持为列表import tkinter as tk
q_a = [
["label 1", [1,2,3,4]],
["label 2", [5,6,7,8]],
]
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.label = tk.Label(self)
self.label.pack()
self.button1 = tk.Button(self, command=self.loop)
self.button1.pack()
self.button2 = tk.Button(self, command=self.loop)
self.button2.pack()
self.button3 = tk.Button(self, command=self.loop)
self.button3.pack()
self.button4 = tk.Button(self, command=self.loop)
self.button4.pack()
self.last = len(q_a)
self.current = -1
# set first text
# because `self.current = -1` then it use `self.current = 0`
self.loop()
def loop(self):
# get next element from list
self.current += 1
if self.current == self.last:
self.label.configure(text="The end")
# hide buttons
self.button1.forget()
self.button2.forget()
self.button3.forget()
self.button4.forget()
else:
self.label['text'] = q_a[self.current][0]
self.button1['text'] = q_a[self.current][1][0]
self.button2['text'] = q_a[self.current][1][1]
self.button3['text'] = q_a[self.current][1][2]
self.button4['text'] = q_a[self.current][1][3]
if __name__ == "__main__":
app = ExampleApp()
app.mainloop()
并使用button[0], etc,
循环来更改所有按钮上的文本或隐藏所有按钮。
BTW:为了提高可读性,您可以使用带有词典的列表
for
和
q_a = [
{"q": "label 1", "a": [1,2,3,4]},
{"q": "label 2", "a": [5,6,7,8]},
]
甚至
else:
self.label['text'] = q_a[self.current]["q"]
self.button1['text'] = q_a[self.current]["a"][0]
self.button2['text'] = q_a[self.current]["a"][1]
self.button3['text'] = q_a[self.current]["a"][2]
self.button4['text'] = q_a[self.current]["a"][3]