我是一名制作基本的迷你Steam客户端的老师,作为我编程班的学习练习。我们正在使用Python和tkinter。
程序将生成两组单选按钮。第一个是用户“游戏库”,他们可以在其中选择要玩的游戏(选择单选按钮时,除了标签会告知用户游戏即将发布外,什么都没有发生)。第二组单选按钮使用户可以选择一个新游戏来“购买”。两组单选按钮均带有for循环和列表。
问题: 我想做的就是拥有它,因此,如果您选择要“购买”的游戏,它将被添加到user_library列表中,然后销毁/忘记原始的游戏库单选按钮集,然后使用for循环重新生成单选按钮。现在,这也应该为新添加的游戏提供一个按钮。
我尝试过的“忘记”代码只能隐藏/删除由for循环生成的最后一个raido按钮。
注意:单选按钮用于演示目的,我知道下拉菜单会更好。
我计划使用一种与“购买”按钮相关的方法来完成此操作。
当我运行程序时,我尝试过的“忘记”代码仅隐藏/删除了由for循环生成的最后一个raidobutton。
以下代码为缩写,但应显示我要执行的操作。我很乐意添加列表,但是不明白为什么只忘记了最后一个单选按钮。
我愿意采用更好的方法来解决问题
libraryGames=["The Witcher 3: Wild Hunt GOTE", "Jurassic World: Evolution", "Red Dead Redemption 2","Mass Effect Trilogy","Subnautica",]
saleGames=["SteamPunk 2077", 29.99, "Fallout 3", 3.99, "Warcraft 4: About dam time", 69.99, "Lego: Terminator", 19.99, "Homework simulator", 14.99]
def __init__(self, parent):
#list that created the library game buttons
for games in range (0, len (libraryGames)):
rb = Radiobutton(frame1, variable = self.library_game, bg =
"#000000",fg="#ffffff", value = games, text =
libraryGames[games],command = self.library_choice)
rb.grid(row = libraryrow, column=0, columnspan = 2,padx=25,
sticky=W,)
libraryrow+=1
#list that created the sale game buttons
for items in range (0, len (saleGames),2):
rb2 = Radiobutton(frame2, variable = self.sale_game, bg =
"#000000",fg="#ffffff",value = items, text =
saleGames[items],command = self.sale_choice)
rb2.grid(row = salerow, column=0, columnspan = 2,padx=25,
sticky=W,)
salerow+=1
#method that removes the radio buttons generated by the first loop when a purchase button is clicked.
def purchase(self):
rb.grid_forget()
# I would then add the loop code to create the radio buttons again
答案 0 :(得分:1)
首先创建一个列表以容纳单选按钮,然后在需要时循环遍历列表以grid_forget
。
import tkinter as tk
root = tk.Tk()
libraryGames=["The Witcher 3: Wild Hunt GOTE", "Jurassic World: Evolution", "Red Dead Redemption 2","Mass Effect Trilogy","Subnautica",]
class GUI:
def __init__(self, parent):
frame1 = tk.Frame(parent)
frame1.pack()
self.holder_list = []
for num,game in enumerate(libraryGames):
rb = tk.Radiobutton(frame1, bg="#000000",fg="#ffffff",
value=game, text=game,command= "",selectcolor="grey")
rb.grid(row = num, column=0, columnspan = 2,padx=25,sticky=tk.W,)
self.holder_list.append(rb)
frame2 = tk.Frame(parent)
frame2.pack()
tk.Button(frame2,text="Purchased",command=self.purchase).pack()
def purchase(self):
print (self.holder_list)
for widget in self.holder_list:
widget.grid_forget()
GUI(root)
root.mainloop()