0

我想在 tkinter 中输入一些数字:18 64 22 5 42 40 48 20 49 33 61 39 62 71。我希望它们看起来像 [18,64,22,5,42,40....]

4

4 回答 4

5

Use text.split() to make a list of strings. The split method will by default split on whitespace. If you want a list of ints, you could use map(int, text.split()):

In [6]: text = '18 64 22 5 42 40 48 20 49 33 61 39 62 71'

In [7]: text.split()
Out[7]: ['18', '64', '22', '5', '42', '40', '48', '20', '49', '33', '61', '39', '62', '71']

In [8]: map(int, text.split())
Out[8]: [18, 64, 22, 5, 42, 40, 48, 20, 49, 33, 61, 39, 62, 71]

And to show how it can be used with Tkinter:

import Tkinter as tk
class App(object):
    def read_entry(self, event):
        entry = event.widget
        text = entry.get()
        print(map(int, text.split()))
    def __init__(self):
        entry = tk.Entry()
        entry.bind('<Return>', self.read_entry)
        entry.pack()
        entry.focus()

root = tk.Tk()
app = App()
root.mainloop()
于 2012-12-09T16:10:44.690 回答
1

你可以使用 list comprehension

In [1]: strs="18 64 22 5 42 40 48 20 49 33 61 39 62 71"

In [2]: [int(x) for x in strs.split()]
Out[2]: [18, 64, 22, 5, 42, 40, 48, 20, 49, 33, 61, 39, 62, 71]
于 2012-12-09T16:25:15.530 回答
0

Try:

map(int, string_numbers.split())

when string_numbers is your space-separated list of numbers.

于 2012-12-09T16:11:15.457 回答
0

精确输出 [18,64,22,5,42,40....] 的函数

def format_nrs(nr_str, n=6):
    nrs = nr_str.split()
    s = ",".join(nrs[:n])
    if n >= len(nrs):
        return "[%s]" % s
    else:
        return "[%s...]" %s

用法 :

n_str = "18 64 22 5 42 40 48 20 49 33 61 39 62 71"

print format_nrs(n_str)
print format_nrs(n_str, 10)
print format_nrs(n_str, 14)

输出:

[18,64,22,5,42,40...]
[18,64,22,5,42,40,48,20,49,33...]
[18,64,22,5,42,40,48,20,49,33,61,39,62,71]
于 2012-12-09T17:41:42.217 回答