使用Tkinter,我试图添加一个用户输入的值,并将其添加到文件中存在的值中,但它不起作用

2024-09-28 21:09:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的小企业创建一个非常简单的忠诚度计划。这是我在Python或Tkinter中的第一个项目

下面的#POINT ENTRY部分允许用户输入适当的点数。然后,它使用“addpoints”从文本文件(扩展名为“.cust”)中提取当前点,添加用户输入的内容并将其写回文本文件

不幸的是,它实际上只是用“.”替换了整条线。!入口26“

任何指导都将不胜感激

#POINT ENTRY
pointlabel = Label(root, text="Enter Earned/Spent Points")
pointlabel.pack()
pointlabel.place(x = 46, y = 95)
pointenter = Entry(root, bg="#E9E9E9")
pointenter.config(font="bold")
pointenter.pack()
pointenter.place(x = 50, y = 120, height="30", width="140")
addbutton = Button(root, bg="green", fg="white", text="   +   ", command=addpoints)
addbutton.config(font='bold')
addbutton.pack()
addbutton.place(x = 201, y = 118)
subbutton = Button(root, bg="red", text="-")
subbutton.config(font='bold')
subbutton.pack()
subbutton.place(x = 251, y = 118)


def addpoints():
    file = open("assets\\" + IDentry.get() + ".cust", 'r+')
    currpts = file.read(0)
    updatepoints = sum(currpts, pointenter)
    file.write(str(updatepoints))
    file.close()

Tags: textconfigplacerootpackfilepointbg
2条回答

下面是一个很好的例子:

尝试:

from tkinter import *
class App:
    def __init__(self, root):
        self.pointenter = Entry(root,font=(None, 14), width=50)
        self.pointenter.pack()
        addbutton = Button(root, bg="green", fg="white", text="   +   ", command=self.addpoints)
        addbutton.config(font='bold')
        addbutton.pack()

    def addpoints(self):
        self.currpts = '50' # a string
        print(float(self.currpts)+ float(self.pointenter.get()))

if __name__=='__main__':
    root = Tk()
    app = App(root)
    root.mainloop()

刚开始的时候我发现一件非常有用的事情就是对所有变量执行print()。希望这有帮助

尝试用.txt扩展名替换.cust扩展名。此外,这里还有一些错误

addpoints()函数应该移到tkinter代码的上方。它在代码的tkinter部分被调用,需要在调用之前定义它

updatepoints = sum(currpts, pointenter)

应该变成:

updatepoints = int(currpts) + int(pointenter.get())

currpts是字符串,需要将其转换为整数pointenter是一个tkinter对象,您需要使用.get()从中获取一个字符串。然后将其转换为整数

另外,我会打开和关闭文件两次,一次读取,一次写入。否则,新的数字只会附加到文件中现有的文本中,而不是替换它

举个例子:

file = open("examplefile.txt", "r")
currpts = file.read(1)
file.close()
print(currpts)
updatepoints = int(currpts) + int(pointenter.get())
print(updatepoints)
writefile = open("test3.txt", "w")
writefile.write(str(updatepoints))
writefile.close()

相关问题 更多 >