繁体   English   中英

Python Tkinter GUI 显示 numpy 阵列中的编号单行

[英]Python Tkinter GUI display numpy array in a numbered single row

我正在尝试将 Python 与 Tkinter 一起使用。 我想要一个 numpy 数组在 GUI 中显示为一长排,其 position 编号但我正在努力弄清楚如何做到这一点。 这是我的 function 用于此操作

     def windspeed():                     

        minSpeed2 = float(minSpeed_entry.get()) # Get value from entry box and converts to float float
        maxSpeed2 = float(maxSpeed_entry.get()) 

        if minSpeed2 >= maxSpeed2:
            tk.messagebox.showinfo("Speed error", "your minimum speed cannot be greater or equal to the max speed") # gives error if max speed is lower than min speed

        windspeed2 = wind_speed(minSpeed2,maxSpeed2)
        windspeed2 = np.round(windspeed2,3)


        shortwindspeed2 = windspeed2[0:10]

        speedbox.delete(1.0, tk.END)
        speedbox.insert(tk.END, shortwindspeed2) # this is where i think the problem is

目前它看起来像这样:

在此处输入图像描述

但是我希望它看起来像这样:

在此处输入图像描述

但是在它旁边的阵列中有 position。

例如:

index 0: 3.8
index 1: 3.9
index 2: 4.0
index 3: 4.1

您希望将 numpy 数组显示为文本并包括索引。

以下代码应该可以解决您的问题:


windspeed2 = np.array([3.8, 3.9, 4.0, 4.1]) # this is just for testing. don't copy this line :)

windspeed2_head = windspeed2[:10] # take the first 10 elements
windspeed2_readable = '\n'.join([f"index {i}: {w}" for i, w in enumerate(windspeed2_head)])

print(windspeed2_readable) 
#speedbox.insert(tk.END, windspeed2_readable)

为了便于重现,我添加了一个print语句,您可以在其中放置speedbox.insert(tk.END, windspeed2_readable)

那么,我们在这里做什么? 使用enumerate语句,我们可以将索引添加到任何可迭代对象。 看这个例子:

 >>> print(list(enumerate("hello")))
  [(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]

为了获得windspeed2_readable ,我们正在遍历windspeed2_head中的枚举值。 我们将当前索引分配给i并将相应的风速分配给w 现在我们使用 f-string 将这两个变量转换为字符串: f"index {i}: {w}"

最后,这部分

 >>> [f"index {i}: {w}" for i, w in enumerate(windspeed2_head)]
 ['index 0: 3.8', 'index 1: 3.9', 'index 2: 4.0', 'index 3: 4.1']

为我们提供了一个字符串列表。 现在我们只需要用换行符'\n'作为分隔符将它们连接起来。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM