【问题标题】:Why is my StringVar not working? please take a look and tell me what I did wrong为什么我的 StringVar 不起作用?请看看并告诉我我做错了什么
【发布时间】:2021-05-05 14:39:32
【问题描述】:
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()

三个多小时以来,我一直试图找出我的错误。我是新手,请耐心等待。

到目前为止,我的文件正在创建中,但该文件不包含我尝试写入其中的任何数据。即使在控制台输出中,我的 bp.get() 也没有返回任何值。

就在几天前,我使用相同格式的代码让另一个类似的应用程序运行,但这不起作用。请帮忙!

这里要求的是 Inputs.py 文件代码:

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()

# .............................

【问题讨论】:

  • 您的代码使用Inputs。那是什么?
  • 这是整个脚本吗?如果没有,您是否可以在创建 bp_entry 后重新分配 bp
  • 它怎么不“工作”?
  • Inputs 是我创建的另一个 python 文件,它使用类似的代码来获取用户的名称和其他信息。此文件导入 Inputs.name 数据以创建文件名。 @BryanOakley
  • @Barmar,是的,这是整个代码,让我感到困惑的是,当 Inputs.py 使用类似的代码并且工作正常时,它是如何不起作用的。

标签: python tkinter tkinter-entry


【解决方案1】:

不需要传递默认值 输入

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

改变

name = tk.StringVar()

在文件中输出

【讨论】:

    【解决方案2】:

    我认为您的主要问题是您忘记为文件指定格式。 无论如何,我已经重写了合并两个文件的代码并实现了更改页面的功能:

        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()
    

    【讨论】:

    • 非常感谢 :) 不胜感激。
    猜你喜欢
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 2014-04-19
    • 2021-07-12
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多