简体   繁体   English

python将列表分配给tk stringvar

[英]python assign list to tk stringvar

I'm having some trouble with stringVars from TK.我在使用 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))

Output is:输出是:

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

As you can see, the format is different.如您所见,格式不同。 Obviously, the list of strings is internally converted into one string with quotes.显然,字符串列表在内部被转换为一个带引号的字符串。 What ist the reason and how can I avoid it?原因是什么,我该如何避免? For my script I would like to have a list of strings for further processing.对于我的脚本,我想要一个字符串列表以供进一步处理。

@tjt263, it's very long time ago, but I think I solved it like @tjt263,很久以前了,但我想我已经解决了

    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)

I am not sure if I remember the issue correctly but I hope it helps you我不确定我是否正确地记住了这个问题,但我希望它可以帮助你

Cheers Jens干杯詹斯

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))

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

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