Ваша проблема в функции def gettxt():
.
Изменить это:
def gettxt():
inputt=txt.get("1.0","end-1c")
print(inputt)
К этому:
def gettxt():
global txt
inputt=txt.get("1.0","end-1c")
print(inputt)
return inputt
Вы можете просто обойти эту функцию, выполнив работу в printrec()
.
Попробуйте вместо этого:
def printrec():
global txt
f = open(r"./receipts.txt", "a")
f.write("\n{}\n".format(txt.get("1.0","end-1c")))
f.close()
В вашем коде есть и другие проблемы. Убедитесь, что вы используете правильный отступ. В вашем gettxt()
у вас есть отступ с 8 пробелами вместо 4. У вас также не должно быть проставок на ваших ярлыках. Вы можете использовать отступы, чтобы получить то, что вы хотите.
Для справки я обновил ваш код до класса и немного его очистил.
Это избавит от необходимости использовать глобальные переменные и даст вам некоторую ссылку на то, что нужно и не требует имени переменной, а также на то, как вы можете распределять объекты с помощью отступов вместо добавления дополнительных меток.
import datetime
from time import strftime
from tkinter import messagebox
# import tkinter as tk helps to prevent an accidental overriding of variable/function names in the namespace.
import tkinter as tk
# Using a class we can get rid of global and manage things much easier using class attributes
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.geometry("500x800")
# This weight helps the widgets in column 0 resize with the window.
self.columnconfigure(0, weight=1)
self.coststr = tk.StringVar()
self.cost = 0
self.coststr.set('£ {}'.format(self.cost))
self.menu = ["Burger", "Chips", "Milkshake"]
self.day = datetime.date.today()
#this label is using `pady` to set the padding below the widget so you do not need spacer labels
tk.Label(self, text="Menu", font='Verdana, 15').grid(row=0, column=0, pady=(0, 20))
self.btn_frame = tk.Frame(self)
self.btn_frame.grid(row=1, column=0)
# These buttons are placed in a frame so they can expand to fit the frame and be all the same size.
tk.Button(self.btn_frame, text="Burger: £1.99", command=self.choiceburger).grid(row=0, column=0, sticky="ew")
tk.Button(self.btn_frame, text="Chips: £1.49", command=self.choicechips).grid(row=1, column=0, sticky="ew")
tk.Button(self.btn_frame, text="Milkshake: £0.99", command=self.choicemilkshake).grid(row=2, column=0, pady=(0, 80), sticky="ew")
self.txt = tk.Text(self)
self.txt.grid(row=2, column=0)
tk.Label(self, textvariable=self.coststr, font='Verdana, 20').grid(row=3, column=0, pady=(0, 40))
tk.Button(self, text="Pay", command=self.pay, font='Verdana, 25').grid(row=4, column=0)
self.txtboxmsg()
def choiceburger(self):
self.cost += 1.99
self.cost = round(self.cost, 2)
self.coststr.set('£ {}'.format(self.cost))
self.txt.insert("end", 'Burger £1.99\n',)
def choicechips(self):
self.cost += 1.49
self.cost = round(self.cost, 2)
self.coststr.set('£ {}'.format(self.cost))
self.txt.insert("end", 'Chips £1.49\n',)
def choicemilkshake(self):
self.cost += 0.99
self.cost = round(self.cost, 2)
self.coststr.set('£ {}'.format(self.cost))
self.txt.insert("end", 'Milkshake £0.99\n',)
def pay(self):
self.txt.insert("end", "Total Charges: ")
self.txt.insert("end", self.coststr.get())
msgbox = messagebox.askokcancel("", "Are You Sure You Want To Buy These Items?")
self.printrec()
if msgbox == True:
self.txt.delete('1.0', "end")
self.cost = 0
self.cost = round(self.cost, 2)
self.coststr.set('£ {}'.format(self.cost))
self.txtboxmsg()
else:
self.destroy()
def txtboxmsg(self):
self.txt.insert("end", strftime("%H:%M:%S "))
self.txt.insert("end", self.day)
self.txt.insert("end", " Jake's Fast Food\n")
def printrec(self):
# this with open statement will also close once the write is complete.
with open(r"./receipts.txt", "a") as f:
# this write statement gets the data directly from txt so you do not need the gettxt() function.
f.write("\n{}\n".format(self.txt.get("1.0","end-1c")))
app = App()
app.mainloop()