首页 > 解决方案 > Python Tkinter 文本小部件中的随机 { }

问题描述

在 Python 中,我使用 Tkinter 并为机器人制作了一个文本小部件以显示随机日期。但由于某种原因,文本小部件在文本中显示随机 { }。我无法弄清楚是什么导致所有 { } 出现。 这是一个截图

执行此操作的代码部分在这里:

self.text_widget = Text(self.ui, width=20, height=2, bg="#f1f1f1", fg="#656565",
                            font=Font1, padx=5, pady=5)
self.text_widget.place(relheight=0.845, relwidth=1, rely=0.08)
self.text_widget.configure(cursor="arrow", state=DISABLED)

# Create Random Date
year = random.randrange(2021, 2121)
    monthd = random.randrange(1, 12)
    if monthd == 1:
        month = "January"
    if monthd == 2:
        month = "Febuary"
    if monthd == 3:
        month = "March"
    if monthd == 4:
        month = "April"
    if monthd == 5:
        month = "May"
    if monthd == 6:
        month = "June"
    if monthd == 7:
        month = "July"
    if monthd == 8:
        month = "August"
    if monthd == 9:
        month = "September"
    if monthd == 10:
        month = "October"
    if monthd == 11:
        month = "November"
    if monthd == 12:
        month = "December"
    date = random.randrange(1, 29)
    answer = ""
    answer = "on " , date , ", " , month , year
    
    

    # Display Date
    msg2 = "Bot:   " , answer ,  "\n\n\n"
    self.text_widget.configure(state=NORMAL)
    self.text_widget.insert(END, msg2)
    self.text_widget.configure(state=DISABLED)
    print("[OK] Self Message Displayed\n")

    self.text_widget.see(END)

有谁知道如何摆脱 {} ?

标签: pythontkinter

解决方案


你的问题似乎是

msg2 = "Bot:   " , answer ,  "\n\n\n"

因为它创建了一个元组。

只需将其更改为

msg2 = "Bot:   " + answer +  "\n\n\n"

我还注意到另一个问题

monthd = random.randrange(1, 12) 

只会返回 1 到 11。

answer有相同的问题msg2,因此有相同的解决方案。


推荐阅读