【问题标题】:TypeError: unsupported operand type(s)s for +: 'StringVar' and 'str' // Create a text fileTypeError: unsupported operand type(s)s for +: 'StringVar' and 'str' // 创建一个文本文件
【发布时间】:2016-03-20 22:52:56
【问题描述】:

我正在尝试创建一个用于创建文本文件的脚本,该文本文件的名称与用户输入的内容相对应。这是我的代码:

from tkinter import*

fenetre = Tk()
def creation():
    open(f1 + '.txt', "w")
Label1 = Label(fenetre, text = 'Nom de votre classe :')
Label1.pack(side = LEFT, padx = 5, pady = 5)
f1 = StringVar()
Champ = Entry(fenetre, textvariable= f1, bg ='bisque', fg='maroon')
Champ.focus_set()
Champ.pack(side = LEFT, padx = 5, pady = 5)
Bouton = Button(fenetre, text ='Valider', command = creation())
Bouton.pack(side = LEFT, padx = 5, pady = 5)
fenetre.mainloop()

但它不起作用并给出以下错误:

TypeError: unsupported operand type(s)s for +: 'StringVar' and 'str'

我成功创建了一次文件,但它没有名字。

【问题讨论】:

    标签: python file text tkinter tkinter-entry


    【解决方案1】:

    当您想使用该值时,您需要调用f1.get()f1 本身不是字符串,而是可以容纳字符串的对象。对其调用get() 方法会返回它所持有的实际字符串。

    def creation():
        open(f1.get() + '.txt', "w")
    

    【讨论】:

    • 非常感谢,我解决了另一个问题,我的脚本在启动时创建了一个文件,我在 Bouton = Button(fenetre, text ='Valider', command = creation ())
    猜你喜欢
    • 2020-04-04
    • 1970-01-01
    • 2023-04-02
    • 2021-03-27
    • 2020-04-14
    • 1970-01-01
    • 2016-04-29
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多