简体   繁体   中英

Python Tkinter GUI display numpy array in a numbered single row

I am trying to use Python with Tkinter. I would like to have a numpy array shown in the GUI as one long row with their position number but I'm struggling to figure out how to do so. This is my function for this operation

     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

Currently it looks like this:

在此处输入图像描述

However I would like it to look like this:

在此处输入图像描述

But with the position in the array next to it.

For example:

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

You want to have a numpy array displayed as text and including the indices.

The following code should solve your problem:


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)

To be easily reproducable, I added a print statement where you would place speedbox.insert(tk.END, windspeed2_readable) .

So, what are we doing here? With the enumerate statement we can add indices to any iterable. See this example:

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

To get windspeed2_readable we are iterating over the enumerated values in windspeed2_head . We are assigning the current index to i and the corresponding wind speed to w . Now we are converting these two variables to a string by using a f-string: f"index {i}: {w}" .

In the end, this part

 >>> [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']

provides us with a list of strings. Now we just have to join them with a newline character '\n' as the separator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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