I made a program to input what I ate and display calories and sugar

Background

Recently, it seems that the sugar-restricted diet is popular, so when I thought I had tried it, I arrived at the Ministry of Education, Culture, Sports, Science and Technology website and started to think that it was just right for the task.

Various data

Download the Standard Tables of Food Composition in Japan Excel (Japanese version) (collective) from Ministry of Education, Culture, Sports, Science and Technology

There is data that is entered as a character string, so please be careful when using it for calculations etc. (sic)

Please note that. Put it in the same directory.

Download the illustration from Illustration and. Rename it to ** fat.png ** and put it in the same directory.

Creating anguish

――It was painful to say from the conclusion I made ――I was reminded of the troublesomeness of GUI --98% of the time it took was suffering from GUI ――CUI is enough for you to make your own ――Tkinter doesn't seem to be very good in the first place (I don't know) ――The determination to make a GUI again has sprung up. ――At first, I wanted to be able to change the size of the window, but I gave up.

GUI part

--The specifications of pack () are still unclear. --I used place () as a compromise. (Time taken: about half a day) --The search field is a little elaborate. (Time taken: about 5 minutes) --Other pack () arguments are messed up. ――I don't know which one you need or don't need, but it's good because it's working! !! !! !!

main.py



self.frame5 = tk.Frame(self.root, width=self.root.winfo_width() * 0.6, height=self.root.winfo_height() * 0.1, bg="#CCFFCC")

self.button2 = tk.Button(
    self.frame5, text="calculate", font=(u'Meiryo', 17), width=40)
self.button2.bind("<Button-1>", self.show_result)

self.frame5.place(x=512, y=648)
self.frame5.pack_propagate(0)
self.button2.pack(expand=True)

self.root.mainloop()

Processing part

--A bug occurred when float was initially set to int ――Judged that all floats are OK ――I think there is a more beautiful method --Judged as impossible due to the balance with GUI (not impossible at all) ――It's good because it's moving! !! !! !!

main.py


self.list2 = self.listbox2.get(0, tk.END)
self.list3 = self.listbox3.get(0, tk.END)
self.list3 = [float(i.replace("(g)", ""))*0.01 for i in self.list3]

self.cal = 0
self.toshitsu = 0
for i in range(len(self.list2)):
    self.number = self.shokuhinmei.index(self.list2[i])
    self.cal += self.eiyolist[self.number][5]*self.list3[i]
    if self.eiyolist[self.number][16] != "Tr":
        self.toshitsu += float(self.eiyolist[self.number]
                                [16])*self.list3[i]

self.frame1.destroy()
self.frame2.destroy()
self.frame3.destroy()
self.frame4.destroy()
self.frame5.destroy()

self.canvas = tk.Canvas(self.root, width=1280, height=720)
self.pngfile = tk.PhotoImage(file="fat.png ")

self.cal = str(round(self.cal, 1)) + "kcal"
self.toshitsu = str(round(self.toshitsu, 1)) + "g"
self.canvas.create_image(400, 400, image=self.pngfile)
self.canvas.create_text(900, 180, text="Calorie intake",
                        font=(u'Meiryo', 60))
self.canvas.create_text(900, 300, text=self.cal,
                        font=(u'Meiryo', 60, "bold"), fill="red")
self.canvas.create_text(900, 420, text="Amount of sugar ingested",
                        font=(u'Meiryo', 60))
self.canvas.create_text(900, 540, text=self.toshitsu,
                        font=(u'Meiryo', 60, "bold"), fill="red")

self.canvas.place(x=0, y=0)

Finished product

--There was no particular problem other than suffering from GUI ――I received advice that it is better to use a method for reuse, so I changed it a little.

main.py


# -*- coding: utf-8 -*-
import tkinter as tk
import time
import re
import xlrd


excel_path = '1365334_1r12.xlsx'
pic_path = "fat.png "


class app():
    def __init__(self, excel_path, pic_path):
        self.pic_path = pic_path
        self.int_seiki = re.compile(r"^[1-9]\d*$")#Compile"
        self.sheet = xlrd.open_workbook(excel_path).sheet_by_name('This table')
        self.eiyolist = [self.sheet.row_values(row)
                         for row in range(self.sheet.nrows) if row > 7]
        self.shokuhinmei = [self.eiyolist[i][3].replace(
            '\u3000', " ") for i in range(len(self.eiyolist))]

        self.root = tk.Tk()
        self.root.geometry("1280x720")
        self.root.title("Calorie calculation")
        self.root.resizable(0, 0)

        self.create()

    def create(self):

        #Variables that must be declared first
        self.juhuku = None
        self.itemid = "None"

        self.root.update_idletasks()  #Magic for loading winfo

        self.frame1 = self.create_pack_frame(self.root, 0.4, 1, "#CCFFCC")
        self.kensaku = self.create_pack_label(self.frame1, "Search")
        self.entry = self.create_pack_entry(self.frame1, bind=(
            '<KeyRelease>', self.show_list), padx=30, pady=5)
        self.kouho = self.create_pack_label(self.frame1, "Candidate")
        self.listbox = self.create_pack_listbox(
            self.frame1, fontsize=10, func=("<Leave>", self.clicked), bg="white", padx=3, pady=5)  #The functions I tried variously worked well with this

        self.gram = self.create_pack_label(self.frame1, "Gram(g)")
        self.gramentry = self.create_pack_entry(
            self.frame1, bind=('<Return>', self.insert), pady=5)

        self.button1 = tk.Button(
            self.frame1, text="Insert", font=(u'Meiryo', 10), width=10)
        self.button1.bind("<Button-1>", self.insert)
        self.button1.place(x=380, y=680)

        # frame2---------------------------------------------------------------
        self.frame2 = self.create_pack_frame(self.root, 0.48, 0.9)
        self.listbox2 = self.create_pack_listbox(self.frame2)

        # frame3---------------------------------------------------------------
        self.frame3 = self.create_pack_frame(self.root, 0.1, 0.9)
        self.listbox3 = self.create_pack_listbox(self.frame3)

        # frame4---------------------------------------------------------------
        self.frame4 = self.create_pack_frame(self.root, 0.02, 0.9)
        self.listbox4 = self.create_pack_listbox(
            self.frame4, bg="pink", func=("<Double-Button-1>", self.deleteC))

        # frame5---------------------------------------------------------------
        self.frame5 = tk.Frame(self.root, width=self.root.winfo_width(
        ) * 0.6, height=self.root.winfo_height() * 0.1, bg="#CCFFCC")

        self.button2 = tk.Button(
            self.frame5, text="calculate", font=(u'Meiryo', 17), width=40)
        self.button2.bind("<Button-1>", self.show_result)

        self.frame5.place(x=512, y=648)
        self.frame5.pack_propagate(0)
        self.button2.pack(expand=True)

        self.root.mainloop()

    def create_pack_entry(self, frame, fontsize=15, bind=None, fill=None, padx=0, pady=0):
        self.New_entry = tk.Entry(frame, font=(u'Meiryo', fontsize))
        if len(bind) == 2:
            self.New_entry.bind(bind[0], bind[1])
        self.New_entry.pack(fill=fill, padx=padx, pady=pady)
        return self.New_entry

    def create_pack_label(self, frame, text, fontsize=15, bg="#CCFFCC"):
        self.label = tk.Label(frame, text=text,
                              font=(u'Meiryo', fontsize), bg=bg)
        self.label.pack()
        return self.label

    def create_pack_frame(self, root, width, height, bg="white"):
        self.New_frame = tk.Frame(root, width=root.winfo_width(
        ) * width, height=root.winfo_height()*height, bg=bg)
        self.New_frame.pack(anchor=tk.NW, side='left', expand=True)
        self.New_frame.pack_propagate(0)
        return self.New_frame

    def create_pack_listbox(self, frame, fontsize=15, bg="#CCFFCC", func=None, padx=0, pady=0, height=20):
        self.New_listbox = tk.Listbox(frame, font=(
            u'Meiryo', fontsize), bg=bg, height=height)
        if func != None:
            self.New_listbox.bind(func[0], func[1])
        self.New_listbox.pack(fill='both', expand=True, padx=padx, pady=pady)
        return self.New_listbox

    def show_list(self, event):
        if self.juhuku == self.entry.get():  #It is heavy if you do it continuously at the time of input, so countermeasures
            return
        self.juhuku = self.entry.get()
        self.select_food = []
        self.listbox.delete(0, tk.END)
        for i in self.shokuhinmei:
            if self.juhuku in i:
                self.listbox.insert(tk.END, i)
                self.select_food.append(i)

    def insert(self, event):
        if len(self.itemid) == 1 and re.match(self.int_seiki, self.gramentry.get()):
            self.listbox2.insert(tk.END, self.select_food[self.itemid[0]])
            self.listbox3.insert(tk.END, self.gramentry.get() + "(g)")
            self.listbox4.insert(tk.END, "✖")

    def clicked(self, event):
        if self.listbox.curselection() == ():  #This way of writing because it disappears if you do not hold it. However, it is inducing a bug
            return
        self.itemid = self.listbox.curselection()

    def deleteC(self, event):
        if self.listbox4.curselection() == ():
            return
        self.listbox2.delete(self.listbox4.curselection()[0])
        self.listbox3.delete(self.listbox4.curselection()[0])
        self.listbox4.delete(self.listbox4.curselection()[0])

    def show_result(self, event):
        self.list2 = self.listbox2.get(0, tk.END)
        self.list3 = self.listbox3.get(0, tk.END)
        self.list3 = [float(i.replace("(g)", ""))*0.01 for i in self.list3]

        self.cal = 0
        self.toshitsu = 0
        for i in range(len(self.list2)):
            self.number = self.shokuhinmei.index(self.list2[i])
            self.cal += self.eiyolist[self.number][5] * self.list3[i]

            self.tansuikabutsu = float(
                self.eiyolist[self.number][16]) if self.eiyolist[self.number][16] != "Tr" else 0

            self.shokumotsuseni = float(self.eiyolist[self.number][20].replace(
                "(", "").replace(")", "").replace("-", "0").replace("Tr", "0"))

            self.sa = self.tansuikabutsu - self.shokumotsuseni
            if self.sa >= 0:
                self.toshitsu += self.sa*self.list3[i]

        self.frame1.destroy()
        self.frame2.destroy()
        self.frame3.destroy()
        self.frame4.destroy()
        self.frame5.destroy()

        self.canvas = tk.Canvas(self.root, width=1280, height=720)
        self.pngfile = tk.PhotoImage(file=self.pic_path)

        self.cal = str(round(self.cal, 1)) + "kcal"
        self.toshitsu = str(round(self.toshitsu, 1)) + "g"
        self.canvas.create_image(400, 400, image=self.pngfile)
        self.canvas.create_text(900, 180, text="Calorie intake",
                                font=(u'Meiryo', 60))
        self.canvas.create_text(900, 300, text=self.cal,
                                font=(u'Meiryo', 60, "bold"), fill="red")
        self.canvas.create_text(900, 420, text="Amount of sugar ingested",
                                font=(u'Meiryo', 60))
        self.canvas.create_text(900, 540, text=self.toshitsu,
                                font=(u'Meiryo', 60, "bold"), fill="red")

        self.canvas.bind("<Double-Button-1>", self.moto)

        self.canvas.place(x=0, y=0)

    def moto(self, event):
        self.canvas.destroy()
        self.create()


if __name__ == "__main__":
    app = app(excel_path, pic_path)

Execution result

スクリーンショット (636).png スクリーンショット (635).png

Conclusion

I'm glad that what I was thinking was in shape. However, I think there are many improvements, so I would like to fix them.

Reference site

Ministry of Education, Culture, Sports, Science and Technology Illustrations Record from the bottom to the top Blog I want to be an engineer

Recommended Posts

I made a program to input what I ate and display calories and sugar
I made a script to display emoji
I made a program to convert images into ASCII art with Python and OpenCV
I made a program to solve (hint) Saizeriya's spot the difference
I tried to create Bulls and Cows with a shell program
I made a command to display a colorful calendar in the terminal
I made a payroll program in Python!
I made a program to notify you by LINE when switches arrive
I made a network to convert black and white images to color images (pix2pix)
I made a program to check the size of a file in Python
I made a tool to notify Slack of Connpass events and made it Terraform
I made a tool to easily display data as a graph by GUI operation.
I made a tool to compile Hy natively
What I thought and learned to study for 100 days at a programming school
I made a tool to get new articles
I made a program to look up words on the window (previous development)
I made a Caesar cryptographic program in Python.
I made a prime number generation program in Python
I made a library to separate Japanese sentences nicely
I made a script to put a snippet in README.md
I made a Python module to translate comment outs
I made a code to convert illustration2vec to keras model
I made a LINE BOT with Python and Heroku
I made a prime number generation program in Python 2
I made a command to markdown the table clipboard
I made a python library to do rolling rank
〇✕ I made a game
I made a toolsver that spits out OS, Python, modules and tool versions to Markdown
I made a tool that makes it a little easier to create and install a public key.
I made a server with Python socket and ssl and tried to access it from a browser
I made a method to automatically select and visualize an appropriate graph for pandas DataFrame
I scraped the Organization member team and made a ranking
I made a package to filter time series with python
I wrote a program quickly to study DI with Python ①
I made a box to rest before Pepper gets tired
I made a command to generate a table comment in Django
I made a function to check the model of DCGAN
I tried to display the time and today's weather w
[Titan Craft] I made a tool to summon a giant to Minecraft
I want to make input () a nice complement in python
I made a Chatbot using LINE Messaging API and Python
I made you to execute a command from a web browser
I made a script to say hello at my Koshien
What to do if you grep a text file and it becomes Binary file (standard input) matches
Shell program to display pyramids
I made a python text
I made a discord bot
I made a simple circuit with Python (AND, OR, NOR, etc.)
I want to record the execution time and keep a log.
I made a library to easily read config files with Python
[Python3] I made a decorator that declares undefined functions and methods.
I made a simple network camera by combining ESP32-CAM and RTSP.
I made a game called Battle Ship using pygame and tkinter
I made a program that solves the spot the difference in seconds
I made a web server with Raspberry Pi to watch anime
Don't you want to say that you made a face recognition program?
I made a Nyanko tweet form with Python, Flask and Heroku
I made RNN learn a sine wave and made a prediction: Hyperparameter adjustment
I tried to make a periodical process with Selenium and Python
I made a prime number table output program in various languages
I want to create a pipfile and reflect it in docker