我想在tkinter中输入一些数字:18 64 22 5 42 40 48 20 49 33 61 39 62 71.我希望它们看起来像[18,64,22,5,42,40 .. ..]
答案 0 :(得分:5)
使用text.split()
制作字符串列表。默认情况下,split method将在空格上分割。如果您想要一个整数列表,可以使用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]
并展示它如何与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()
答案 1 :(得分: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]
答案 2 :(得分:0)
尝试:
map(int, string_numbers.split())
当string_numbers
是以空格分隔的数字列表时。
答案 3 :(得分: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]