简体   繁体   中英

How do I get the GUI to print out C and D in the label and not {C and D}? Python Tkinter

On the GUI when the code chooses 'C and D', the output on label looks like {C and D}. Is there a way to get rid of the {} and have it just print out C and D? Preferably without having to add more elements to the list.

from tkinter import *
root= Tk()
root.title('Letters')
def test():
    import random
    letter=['A','B','C and D']
    letterslist=list()
    count = 0
    while count <5:
        y= random.choice(letter)
        letterslist.append(y)
        count=count+1
    return letterslist
x=test()
label1 =Label(root, text = x , fg="White", bg="Orange" )
label1.pack()
root.mainloop()

You could join all the elements of the list with:

return ' '.join(letterlist)

Your code would look like this now.

from tkinter import *
root= Tk()
root.title('Letters')
def test():
    import random
    letter=['A','B','C and D']
    letterslist=list()
    count = 0
    while count <5:
        y= random.choice(letter)
        letterslist.append(y)
        count=count+1
    return ' '.join(letterslist)
x=test()
label1 =Label(root, text = x , fg="White", bg="Orange" )
label1.pack()
root.mainloop()

Do this:

from tkinter import *
root= Tk()
root.title('Letters')
def test():
    import random
    letter=['A','B','C and D']
    letterslist=list()
    count = 0
    S=""
    while count <5:
        y= random.choice(letter)
        letterslist.append(y)
        count=count+1
        S=S+str(y)
        if count !=5:
            S=S+","

    print (S, letterslist)
    return S
x=test()
label1 =Label(root, text = x , fg="White", bg="Orange" )
label1.pack()
root.mainloop()

You can remove the lines with letterslist. I didn't delete them, so that you can compare.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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