Python如何向列表中的新值添加用户条目?

2024-04-19 04:56:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的Tkinter条目。在

当用户输入一个条目并按下GUI上的按钮时,我希望它将用户条目添加到名为self.players的列表中。在

这在一定程度上是有效的。条目被添加到列表中,但是当我输入第二个条目并按下按钮时,它会替换列表中的第一个条目,而不是像我想要的那样将其作为第二个条目添加到列表中。在

我怎样才能使条目每次都被添加到一个新值。 谢谢

我的代码是:

import tkinter
from tkinter import ttk

class Application(object):

    def __init__(self):
        self.root = tkinter.Tk()

        self.welcomeLabel = tkinter.Label(text = "Welcome to Darts!")
        self.welcomeLabel.grid(row=1, column=0)

        self.playerLabel = tkinter.Label(text = ("Type in Player names!"))
        self.playerLabel.grid(row=2, column=0)

        self.playerEntry = tkinter.Entry()
        self.playerEntry.grid(row=3, column=0)

        self.playGameButton = tkinter.Button(text = "Play", command = self.game_button)
        self.playGameButton.grid(row=4, column=0)


    def game_button(self):
        self.players = []

        playerData = self.playerEntry.get()

        self.players = (playerData)

        print (self.players)

myApp = Application()
myApp.root.mainloop()

Tags: text用户importself列表applicationtkinterdef
1条回答
网友
1楼 · 发布于 2024-04-19 04:56:19

使用append

self.players.append(playerData)

当前代码只是用新信息覆盖列表中已存储的数据。

这就是为什么列表中的信息只是最新的条目。append将其添加到列表中已有的信息中。在

参考文献

https://docs.python.org/2/tutorial/datastructures.html

相关问题 更多 >