gpt4 book ai didi

python - 我想在条目中输入一个值,按下按钮并将该值保存在 var 中,并使用该值创建一个 .txt 文件,但它不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:31 25 4
gpt4 key购买 nike

首先,如果我在文字中写了很多错误,请原谅,英语不是我的母语,提前致谢。其次,我是 Python 和 Tkinter 的新手,我看过一些 YouTube 视频,并且正在按照一些教程来执行此操作。

我正在尝试创建一个软件,在按下按钮生成该值后,它应该接收我通过 Entry 输入的值,将该值保存在变量中并使用该值生成一个新的 document.txt我介绍过。

我尝试用以下方法更改线路:- idcheck=StringVar() 到 idcheck = str(),但在控制台中它显示: AttributeError: 'str'object has no attribute 'get'.

这是代码,我已尝试最大程度地减少代码量,以便您可以尝试执行并检查发生了什么。

from tkinter import *

window = Tk()

def funcion():
print("ID: ", idcheck.get()) #To make sure that the value I'm entering is correct

window.title("app")
Label(window, text="ID").grid(padx=10 ,pady=10, row=0, column=0)

idcheck = StringVar() #this is giving me troubles when I do next step (.write says it must be str() not StringVar()

Entry(window, textvariable=idcheck, width=30).grid(padx=5, row=0, column=1, sticky=E+W)
Button(window, text="Generate", width=30, command=funcion).grid(padx=10,pady=10,row=2,column=0,columnspan=2,sticky=E+W)

idchecklist = open("document.txt","w")
idchecklist.write(idcheck.get())
idchecklist.close()

window.mainloop()

我希望获得我在新​​文档的 Entry 中引入的值,但实际输出是创建一个 document.txt 但它是空的(我不知道如何获取该值)。

我还能尝试什么?谢谢。

最佳答案

写入文件的逻辑位于函数之外。当您执行 python 程序时,它甚至在用户单击“生成”按钮之前就创建了文件 document.txt,并且此时 idecheck 为空,这就是该文件为空的原因。当用户单击“生成”按钮时,您可以移动此逻辑,如下所示

def funcion():
print("ID: ", idcheck.get()) # To make sure that the value I'm entering is correct
idchecklist = open("document.txt", "w")
idchecklist.write(idcheck.get())
idchecklist.close()

关于python - 我想在条目中输入一个值,按下按钮并将该值保存在 var 中,并使用该值创建一个 .txt 文件,但它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58411911/

25 4 0
文章推荐: css - 从 div 中删除 body 的背景图像
文章推荐: jQuery 在动态类型模式中为每个 li 赋予一定的背景颜色
文章推荐: html - CSS - 将 置于透明的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com