Home > database >  Python tKinter adds apostrophe to list
Python tKinter adds apostrophe to list

Time:01-27

I'm working on an Python script with a GUI. I can read out some colors using get().

The problem is that when I want to use these colors to draw shapes using PIL, Python adds apostrophes to the beginning and end of the list.

def add_color_lines():
    the_color=tab_lines_colors_input.get()
    lines_color_list.append(the_color)
    print(lines_color_list)

This is the output:

'"white","black","grey"'

I want it to be:

"white","black","grey"

What am I doing wrong? Why does the script add apostrophes to the list?

This is what I add:

This is what I add

This is what I get. Notice the apostrophes next to the brackets. This is what I get. Notice the apostrophes after the brackets.

PIL cannot work with this because it says:

ValueError: unknown color specifier: '"white","black","grey"'

CodePudding user response:

You can parse the string it's giving with the split() function.

output = lines_color_list.split(",")

This should output this list

['"white"', '"black"', '"gray"']

CodePudding user response:

Alright, as mentioned by @acw1668 when you get the input form the text, it should just be color without quotes. white,black,grey

Now, in change the code to use the_color.split(",") and append that values to the list using lines_color_list = the_color.split(",")

lines_color_list = []
def add_color_lines():
    the_color=tab_lines_colors_input.get()
    lines_color_list  = the_color.split(",")
    print(lines_color_list)

The reason of apostrophe/single quote (') is how print function prints string elements of a list. Try this out to see how it prints.

Sample 1: # Three elements in a list my_list = ["a", "b", "c"] print(my_list)

output

 ['a', 'b', 'c']

Sample 2:

 # Three element in a list
 my_list = ['a', 'b', 'c']
 print(my_list)

output

 ['a', 'b', 'c']

Sample 3:

 # One element in a list
 my_list = ["a, b, c"]
 print(my_list)

output

 ['a, b, c']

Sample 4 (your current scenario):

my_list = []
my_text = '"a", "b", "c"'
my_list.append(my_text) # Single element in the list
print(my_list)

output ['"a, b, c"']

  •  Tags:  
  • Related