1
import tkinter as tk
import datetime
import Inputs
import os


today = datetime.datetime.now()
today = today.strftime("%Y%m%d%H%M%S")

root = tk.Tk()
root.geometry("500x600")
root.title("General Examination of the Patient")

bp = tk.StringVar()


def submited():
    new_file = f"{Inputs.name.get()}_trial"
    path = Inputs.path
    fullpath = os.path.join(path, new_file)
    with open(fullpath, "w") as gpe:
        gpe.write(bp.get() + "\n")
    root.quit()
    print(bp.get())


ga_label = tk.Label(root, text="GA")
bp_label = tk.Label(root, text="Blood Pressure")

ga_label.grid(columnspan=3, row=0)
bp_label.grid(column=0, row=1)

bp_entry = tk.Entry(root, textvariable=bp)
bp_entry.grid(column=1, row=1)

submit_btn = tk.Button(root, text="Submit", command=submited)
submit_btn.grid(columnspan=2, row=6)


root.mainloop()

I have tried to find my error for more than three hours. I am a complete newbie so please be patient with me.

so far, my files are getting created, but the file does not contain any of the data I am trying to write in them. even in the console output my bp.get() is not returning any value.

Just few days back I used this same format of code to get another similar app working but this does not work. Please help!

As requested here is the Inputs.py file code:

import datetime
import tkinter as tk
import os
import datetime

today = datetime.datetime.now()
today = today.strftime("%Y%m%d%H%M%S")
# today = str(today)

basicdetails = tk.Tk()

#  Basic patient details
name = tk.StringVar(basicdetails, value="Name")
age = tk.StringVar()
gender = tk.StringVar()
height = tk.StringVar()
weight = tk.StringVar()
diet = tk.StringVar()
ethnicity = tk.StringVar()
occupation = tk.StringVar()
residence = tk.StringVar()
contact = tk.StringVar()

path = ""


def submit():
    global path
    new_file = f"{name.get()}_basicdetails_{today}"
    path = f"E:/PythonProjects/ambiproj/Data/{name.get()}_{today}"
    try:
        os.mkdir(path)
    except FileExistsError:
        pass
    fullpath = os.path.join(path, new_file)
    with open(fullpath, "w") as s:
        s.write(name.get() + "\n")
        s.write(age.get() + "\n")
        s.write(gender.get() + "\n")
        s.write(height.get() + "\n")
        s.write(weight.get() + "\n")
        s.write(occupation.get() + "\n")
        s.write(ethnicity.get() + "\n")
        s.write(residence.get() + "\n")
        s.write(contact.get() + "\n")
    basicdetails.quit()

# Page 1: Basic Details

# name = tk.StringVar(root, value="Name")
# age = tk.StringVar()
# gender = tk.StringVar()
# height = tk.StringVar()
# weight = tk.StringVar()
# diet = tk.StringVar()
# ethnicity = tk.StringVar()
# occupation = tk.StringVar()
# residence = tk.StringVar()
# contact = tk.StringVar()

# Page 2: Additional details (to be entered later)

namebox = tk.Entry(basicdetails, textvariable=name).grid(row=0, column=1)
agebox= tk.Entry(basicdetails, textvariable=age).grid(row=1, column=1)
genderbox = tk.Entry(basicdetails, textvariable=gender).grid(row=2, column=1)
heighbox = tk.Entry(basicdetails, textvariable=height).grid(row=3, column=1)
weightwb = tk.Entry(basicdetails, textvariable=weight).grid(row=4, column=1)
dietbox = tk.Entry(basicdetails, textvariable=diet).grid(row=5, column=1)
ethnicitybox = tk.Entry(basicdetails, textvariable=ethnicity).grid(row=6, column=1)
occubox = tk.Entry(basicdetails, textvariable=occupation).grid(row=7, column=1)
contactbox = tk.Entry(basicdetails, textvariable=contact).grid(row=8, column=1)
submitbut = tk.Button(basicdetails, text="Submit", font="Verdana", command=submit).grid(row=9, columnspan=2)


basicdetails.mainloop()

# .............................
  • 1
    Your code uses `Inputs`. What is that? – Bryan Oakley May 05 '21 at 14:47
  • Is this the whole script? If not, could you have reassigned `bp` after you created `bp_entry`? – Barmar May 05 '21 at 15:00
  • 2
    How is it not 'working'? – norie May 05 '21 at 15:05
  • Inputs is another python file I created which uses similar code to get name and other info of a user. This file imports the Inputs.name data to create the file name. @BryanOakley – user15843822 May 05 '21 at 15:10
  • @Barmar, yes this is the whole code, perplexes me how this is not working when the Inputs.py uses similar code and works just fine. – user15843822 May 05 '21 at 15:11
  • @norie, it is not working as in my file does not get bp.get() data the user inputs. the textfile is saved empty, just as my console output is empty. I do not get errors either. – user15843822 May 05 '21 at 15:13
  • Include `Inputs`. Thanks. – Skarlett May 05 '21 at 15:13
  • I removed the Inputs stuff from your code and tried it, and it worked fine for me. What happens when you try that? – Barmar May 05 '21 at 15:16
  • @Skarlett, thank you. I have now included it in my question. – user15843822 May 05 '21 at 15:16
  • @Barmar, it works for me too. But I want it work along with Inputs so that I can organise all the different files neatly in single folder per user. – user15843822 May 05 '21 at 15:19
  • I reproduced the problem when I copied your Inputs.py (and changed `path` to work on my computer). – Barmar May 05 '21 at 15:22
  • @Barmar, that suggests that the problem is in Inputs maybe? or maybe I am going wrong way about integrating them? this is all too new for me. Please do reply if you can pin point the problem. Thanks a ton :) – user15843822 May 05 '21 at 15:24
  • `bp = tk.StringVar(root)` fixes it. I guess loading `Input` is changing how this argument defaults. – Barmar May 05 '21 at 15:34
  • It is because the instance of `Tk()` is not destroyed when `basicdetails.quit()` is called. So there are two instances of `Tk()` when `root` is created. – acw1668 May 05 '21 at 15:38
  • @Barmar, thank you very much. I think you are right that Inputs is somehow messing it up. I will apply this fix. Appreciate your time. Have a great time! – user15843822 May 05 '21 at 15:38
  • @acw1668, I changed basicdetails.quit() to .destroy() and it worked. Thanks a lot. That makes it much easier. Would you also please explain the difference between .quit and .destroy in this case? I appreciate your input. – user15843822 May 05 '21 at 15:42
  • See [difference-between-quit-and-destroy-on-tkinter](https://stackoverflow.com/questions/63271131/difference-between-quit-and-destroy-on-tkinter). – acw1668 May 05 '21 at 15:47
  • Your code works for me.... –  May 05 '21 at 19:31

2 Answers2

0

don't need to pass default value input

name = tk.StringVar(basicdetails, value="Name") 

to change

name = tk.StringVar()

Your output

output in file

output file

Ramesh
  • 504
  • 5
  • 9
0

I think your main problem is that you've forgot to give a format to your file. Anyway I have rewritten the code merged both files and implemented a function to change the page:

enter image description here enter image description here enter image description here

    try:
    import tkinter as tk                # python 3
    from tkinter import font as tkfont  # python 3
except ImportError:
    import Tkinter as tk     # python 2
    import tkFont as tkfont  # python 2
import os
import datetime


def get_date():
    return datetime.datetime.now().strftime("%Y%m%d%H%M%S")


class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.patient_name = "Unknown"
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        self.frames = {}
        for F in (BasicInfo, BloodPressure, AdditionalInfo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame("BasicInfo")

    def show_frame(self, page_name):
        """
        Shows a frame for the given page name
        """
        frame = self.frames[page_name]
        frame.tkraise()

    def submit_to_patient_file(self, str_to_submit):
        new_file = f"{self.patient_name}_basicdetails_{get_date()}.txt"
        path = os.path.join("E:", "PythonProjects", "ambiproj", "Data",)
        path = os.path.join(path, "{name}_{today}".format(name=self.patient_name, today=get_date()))
        if not os.path.isdir(path):
            os.mkdir(path)
        with open(os.path.join(path, new_file), "w") as file:
            file.write(str_to_submit)
        file.close()


class BasicInfo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.controller = controller
        label = tk.Label(self, text="This is the starting page \n Please enter patients information and press submit! ")
        label.grid(row=0, column=0, columnspan=2)
        basic_info_list = ["name", "age", "gender", "height", "weight", "diet", "ethnicity", "occupation", "residence", "contact"]
        self.dict_entry = {}
        row = 1
        for info in basic_info_list:
            tk.Label(self, text=info).grid(row=row, column=0, )
            new_entry = tk.Entry(self, )
            new_entry.grid(row=row, column=1)
            self.dict_entry[info] = new_entry
            row += 1

        submit_but = tk.Button(self, text="Submit", command=self.submit)
        submit_but.grid(row=row+1, column=0, columnspan=2, pady=5)

    def submit(self):
        file_str = ""
        if self.dict_entry["name"].get() != "":
            self.controller.patient_name = self.dict_entry["name"].get()
        for key in self.dict_entry:
            file_str += key + " : " + self.dict_entry[key].get() + "\n"

        self.controller.submit_to_patient_file(file_str)
        self.controller.show_frame("BloodPressure")


class BloodPressure(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.controller = controller
        label = tk.Label(self, text="This is the 2nd page \n Please enter patients blood pressure and press submit! ")
        label.pack(side="top", fill="x", pady=10)
        bp_label = tk.Label(self, text="Blood Pressure")
        bp_label.pack()
        self.bp_entry = tk.Entry(self, )
        self.bp_entry.pack()
        submit_but = tk.Button(self, text="Submit", command=self.submit)
        submit_but.pack(pady=5)
        button = tk.Button(self, text="Go to the start page", command=lambda: controller.show_frame("BasicInfo"))
        button.pack()

    def submit(self):
        file_str = ""
        file_str += "Blood pressure" + " : " + self.bp_entry.get() + "\n"
        self.controller.submit_to_patient_file(file_str)
        self.controller.show_frame("AdditionalInfo")


class AdditionalInfo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.controller = controller
        label = tk.Label(self, text="This is the 3rd page \n You can repeat the same thing in this page")
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go back to the start page", command=lambda: controller.show_frame("BasicInfo"))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.geometry("300x350")
    app.title("General Examination of the Patient")
    app.mainloop()
Parsa Hz
  • 61
  • 4