简体   繁体   English

Tkinter标签的消毒清单

[英]Sanitizing list for Tkinter label

I'm trying to build a simple name generator as a project, and I've got it to work, but it doesn't output correctly I'm getting outputs like this: 我正在尝试将一个简单的名称生成器作为一个项目来构建,并且已经可以正常工作,但是它无法正确输出,但我得到的输出是这样的:

{NameA}{NameB}NameC NameD{NameE}

While I know for a fact that they are being stored in a list like this: 虽然我知道它们存储在这样的列表中的事实:

['Name A', 'NameB', 'NameC', 'NameD', 'NameE']

Here is the full code: 这是完整的代码:

import tkinter as tk
import random

printout = []

def generate():
for _ in range(var1.get()):
    C = random.randrange(6)

    if C == 0:
        printout.append(random.choice(Prefix))
    elif 1 <= C <= 2:
        printout.append(random.choice(Prefix)+random.choice(Suffix))
    elif 3 <= C <= 5:
        printout.append(random.choice(Prefix)+" "+random.choice(Prefix)+random.choice(Suffix))
var.set(printout)
print(printout)

root = tk.Tk()
root.title("Simple GUI")
root.geometry("200x200")

var = tk.StringVar()

app = tk.Frame(root)
app.grid()

list1 = [1, 5, 10, 50]
var1 = tk.IntVar(app)
var1.set(1)
drop = tk.OptionMenu(root,var1,*list1)
drop.grid()

label = tk.Label(app, text = "How many results:")
label.grid()

button1 = tk.Button(app, text = "Generate!", command=generate)
button1.grid()


label2= tk.Label(app, textvariable=var)
label2.grid()

with open('D:/My Documents/prefix.txt') as f:
Prefix = [line.rstrip('\n') for line in f]
with open('D:/My Documents/suffix.txt') as r:
Suffix = [line.rstrip('\n') for line in r]

root.mainloop()

I can't find anyone have this problem online so I'm not sure what's happening. 我找不到任何人在网上遇到这个问题,所以我不确定发生了什么。

The curly braces you see in your output are a result of Tkinter trying to print a list as if it were a string. 您在输出中看到的花括号是Tkinter试图将列表打印为字符串的结果。 You should explicitly convert your list to a string before passing it to var.set . 在将列表传递给var.set之前,应将其明确转换为字符串。

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

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