【问题标题】:Show array in listbox在列表框中显示数组
【发布时间】:2016-05-09 15:23:16
【问题描述】:

谁能告诉我我做错了什么?!我在 Python 3 中使用 tkinter 制作了一个 GUI。我正在尝试创建数组并在窗口打开时将其显示到列表框。您可以在下面看到我使用的代码。

错误

Population.X[i] = float(random.random()) * self.XMin
IndexError: list assignment index out of range

代码:

class Population:
    X = []
    Y = []

class Application(Frame):
   def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.widgets()
        self.create_array()

   def widgets(self):
        self.first_listbox = Listbox(self)
        self.first_listbox.grid()

   def create_array(self):
        i = 0
        while i < 20:
            Population.X[i] = float(random.random()) * self.XMin
            # x = random.random() - Random float x | 0.0 <= x < 1.0 |
            if Population.X[i] == 0:
                Population.X[i] = -0.1
            Population.Y[i] = 1 / Population.X[i]
            i += 1
        while i < 20:
            self.first_listbox.insert(i, Population.X[i])
            i += 1

root = Tk()
root.geometry("600x400")
app = Application(root)
root.mainloop()

【问题讨论】:

    标签: python arrays python-3.x tkinter listbox


    【解决方案1】:

    附加到列表

    你得到一个IndexError,因为你试图访问元素号0,而你的列表没有元素。

    您不能像这样创建新索引:

    my_list = []
    my_list[12] = 'whatever'
    

    但你可以迭代地追加到列表中:

    def create_array(self):
    
        for i in range(20):
    
            new_item = float(random.random()) * self.XMin)
    
            if new_item == 0:
                new_item = -0.1
    
            Population.X.append(new_item)
            Population.Y.append(1 / new_item)
    

    填充列表框

    此外,您的这部分代码将永远无法访问:

        while i < 20:
            self.first_listbox.insert(i, Population.X[i])
            i += 1
    

    因为退出前一个循环时i20。您需要将 i 设置回 0 或更好地重新考虑整个事情:

    for item in Population.X:
        self.first_listbox.insert(END, item)
    

    小风格备注

    注意

            new_item = float(random.random()) * self.XMin)
    
            if new_item == 0:
                new_item = -0.1
    

    可以写成一行:

            new_item = float(random.random()) * self.XMin) or -0.1
    

    但前者完全没问题,更容易掌握。这主要是口味问题。

    【讨论】:

    • 感谢您的详细解答!我需要说我是 Python 新手,仍然有 Java 开发人员的思维方式。需要更多的 Python 练习。祝你有美好的一天! =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多