Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python将列表分配给tk stringvar_Python_List_Tkinter - Fatal编程技术网

python将列表分配给tk stringvar

python将列表分配给tk stringvar,python,list,tkinter,Python,List,Tkinter,我和TK的stringVars有点麻烦 from tkinter import * root = Tk() strVar = StringVar() tmp1 = ['one','two','three'] print(tmp1) print(len(tmp1)) strVar.set(tmp1) tmp2=strVar.get() print(tmp2) print(len(tmp2)) 输出为: ['one', 'two', 'three'] 3 ('one', 'two', 'th

我和TK的stringVars有点麻烦

from tkinter import *

root = Tk()
strVar = StringVar()
tmp1 = ['one','two','three']
print(tmp1)
print(len(tmp1))

strVar.set(tmp1)
tmp2=strVar.get()
print(tmp2)
print(len(tmp2))
输出为:

['one', 'two', 'three'] 
3
('one', 'two', 'three')
23

正如您所看到的,格式是不同的。显然,字符串列表在内部转换为一个带引号的字符串。原因是什么?我如何避免?对于我的脚本,我希望有一个字符串列表以供进一步处理。

@tjt263,这是很久以前的事了,但我想我像这样解决了它

from tkinter import *
import ast

root = Tk()
strVar = StringVar()
tmp1 = ['one','two','three']
print(type(tmp1), tmp1, len(tmp1))

strVar.set(tmp1)
x = ast.literal_eval('[' + strVar.get()[1:-1] + ']')
print(type(x), x, len(x))
    fdupesSV.set(fdupesList)
    tmp = subprocess.run(['fdupes', '-r',directory.get()], stdout=subprocess.PIPE)

    #first convert bytes to ascii, then split at '\n', then assign so fdupesOut
    fdupesList=tmp.stdout.decode('ascii').split('\n')
    fdupesSV.set(fdupesList)
我不确定我是否正确地记住了这个问题,但我希望它能帮助您

干杯
Jens

虽然将列表分配给字符串变量的想法很有趣,但这实际上不是一个坏问题,到底发生了什么?为什么列表首先转换为元组,然后转换为字符串?例如,如果您将一个数字或dict传递给string var,则这些数字或dict仅转换为str。为什么您觉得需要将字符串列表保存在
StringVar
中?只使用普通python列表有什么错?更好的方法可能是让用户输入一些由特殊字符(空格、逗号、分号等)分隔的字符串,然后相应地
str.split
strVar.get()的值。这比必须输入所有那些
[
'
等更容易使用。您好,感谢您的回复,我必须承认我对python非常陌生,尤其是对TK。背景是我从系统命令中获得字符串列表,如result=subprocess.run(['.']).stdout.decode('ascii'))我通过StringVar将其传递到一个列表框。稍后我想从这个StringVar获取数据以进一步使用它。@Jensenmann:您不需要使用
StringVar
将数据移入和移出列表框。您好,谢谢您的帖子。即使这样做有效,在我看来也不是很干净。背景是我从一个系统中获得了一个字符串列表类似于stem命令的result=subprocess.run(['…')).stdout.decode('ascii'))我通过StringVar将其传递给listbox。我现在了解到StringVar不是用来保存任何列表的,所以我认为我应该将列表保存在一个单独的python列表变量中,并在为listbox设置StringVar之前将列表转换为字符串。@Jensenmann,嗨,这正是我试图做的。你找到了一个好的解决方案吗@tjt263,请在上面找到我的答案