簡體   English   中英

更新/刷新python Tkinter框架

[英]Updating/Refreshing python Tkinter Frames

我目前正在從事一個有關財務應用程序計算工資的小項目。 我在pyCharm中使用tkinter小部件成功創建了多個頁面。 在成功設計了幾個主要頁面並且使代碼能夠運行和執行之后,我遇到了一個問題,即我的頁面或框架是靜態的,並且不刷新。 案例示例:我將單擊“添加員工”,這將打開添加框架,並填寫三個輸入頁面。 提交后,我的數據庫將使用插入進行更新,程序將檢查該Employee是否存在,並相應地執行該函數。 但是,顯示數據庫中所有雇員的我的主頁列表框在返回到框架時不會與新雇員一起更新。 我一直在網上尋找,似乎無法找到解決此問題的方法,因為到目前為止update()不適用於我,除非我使用它絕對錯誤。

我真的可以使用一些幫助,並希望對此提供一些指導。

我將如何刷新我的主頁以及該頁面中的任何頁面,因為輸入框中的輸入似乎也不會偏離注冊框(當我再次導航回它們時)

import tkinter
import tkinter as tk  # python 3
from tkinter import font  as tkfont, Entry, END  # python 3
# import Tkinter as tk     # python 2
# import tkFont as tkfont  # python 2
from tkinter import messagebox
import Employee
import pymysql.cursors
from pymysql.connections import Connection


class GUI(tk.Tk):
    def __init__(self, *args):
        tk.Tk.__init__(self, *args)
        self.shared_data = {
            "first_name": tk.StringVar(),
            "last_name": tk.StringVar(),
            "age": tk.StringVar(),
            "address": tk.StringVar(),
            "day_of_birth": tk.StringVar(),
            "month_of_birth": tk.StringVar(),
            "year_of_birth": tk.StringVar(),
            "health_care": tk.StringVar(),
            "health_care_id": tk.StringVar(),
            "employee_id": tk.StringVar(),
            "married": tk.StringVar(),
            "hInsurance": tk.StringVar(),
            "dInsurance": tk.StringVar(),
            "oInsurance": tk.StringVar(),
            "hTier": tk.StringVar(),
            "four01k": tk.StringVar(),
            "kContribution": tk.StringVar(),
            "pension": tk.StringVar(),
            "unionDues": tk.StringVar(),
            "payType": tk.StringVar(),
            "payAmount": tk.StringVar(),
        }

        tk.Tk.wm_title(self, "Payroll Application")

        #Creation of all the relevant Frames

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(200, weight=1)
        container.grid_columnconfigure(200, weight=1)

        self.frames = {}

        for F in (LoginPage, mainMenuPage, addEmpFrame, addEmpFrame1, addEmpFrame2, removeEmpFrame, EmpLookupFrame,
                  calcPayRollFrame):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.raise_frame(LoginPage)

        #Frame manipulation functions

    def raise_frame(self, page_name):
        frame = self.frames[page_name]
        frame.tkraise()

    def update_frame(self, page_name):
        frame = self.frames[page_name]
        frame.update()

    def destroy_frame(self, page_name):
        frame = self.frames[page_name]
        frame.destroy()

#Frame Designs
#Each frame  written in a class format

class LoginPage(tk.Frame): #Login page Frame
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.label_username = tk.Label(self, text="Username")
        self.label_password = tk.Label(self, text="Password")

        self.entry_username = tk.Entry(self)
        self.entry_password = tk.Entry(self, show="*")

        self.label_username.grid(row=0, column=0)
        self.label_password.grid(row=1, column=0)
        self.entry_username.grid(row=0, column=1)
        self.entry_password.grid(row=1, column=1)

        self.checkbox = tk.Checkbutton(self, text="Keep me logged in")
        self.checkbox.grid(columnspan=2)

        self.loginButton = tk.Button(self, text="Login", command=lambda: controller.raise_frame(self.submitLogin()))
        self.loginButton.grid(columnspan=2)

    def submitLogin(self):
        l = self.entry_username.get()
        p = self.entry_password.get()
        attempt = Employee.Login(l, p)
        attempt.databaseSearchId(attempt.get_temp_id())
        if (attempt.check_login() == 1):
            return mainMenuPage
        elif (attempt.check_login() == 0):
            return LoginPage


class mainMenuPage(tk.Frame): #Main Menu Frame, consists of the main navigation page, List box
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.controller = controller
        self.row = []


        self.scrollbar = tk.Scrollbar(self)
        self.scrollbar.grid(row = 2, column= 2)

        connection: Connection = pymysql.connect(host='localhost',
                                                 port=3306,
                                                 user='root',
                                                 password='root',
                                                 db='hrdb')
        cursorObject = connection.cursor()
        cursorObject.execute('SELECT `firstName`,`lastName` from `employeeprofile`')
        numrows = int(cursorObject.rowcount)
        for x in range(0, numrows):
            self.row.append(cursorObject.fetchone())

        self.list1 = tk.Listbox(self, height=10, width=35)
        for x in self.row:
            self.list1.insert(END, x)
        self.list1.grid(row=2, column=0, columnspan=2)

        self.scrollbar.config(command=self.list1.yview)

        self.label = tk.Label(self, text="Search employee by typing his/her last name:")
        self.label.grid(row=0, column=1)

        self.entry_username = tk.Entry(self)
        self.entry_username.grid(row=0, column=3)


        button = tk.Button(self, text='Add Employee', width=15,
                            command=lambda: controller.raise_frame(addEmpFrame))
        button.grid(row=2, column=3)
        button = tk.Button(self, text='Remove Employee', width=15, command=lambda: controller.raise_frame(removeEmpFrame))
        button.grid(row=3, column=3)
        button = tk.Button(self, text='Employee Lookup', width=15, command=lambda: controller.raise_frame(EmpLookupFrame))
        button.grid(row=4, column=3)
        button = tk.Button(self, text='Calculate Pay Roll', width=15, command=lambda: controller.raise_frame(calcPayRollFrame))
        button.grid(row=5, column=3)






class addEmpFrame(tk.Frame): #One of the three registration Frames, Button NEXT moves to the next registration page
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.controller = controller

        empInfoLabel = tk.Label(self, text='Please enter Personal information.')
        empInfoLabel.grid(row=0, column=1)

        labelFirstName = tk.Label(self, text="Employee First Name")
        labelFirstName.grid(row=1, column=0)
        labelLastName = tk.Label(self, text="Employee Last Name")
        labelLastName.grid(row=2, column=0)
        labelAge = tk.Label(self, text="Employee Age")
        labelAge.grid(row=3, column=0)
        labelAddress = tk.Label(self, text="Employee full address?(street, city, state, zip")
        labelAddress.grid(row=4, column=0)
        labelDOB = tk.Label(self, text="Employee day of birth")
        labelDOB.grid(row=5, column=0)
        labelMOB = tk.Label(self, text="Employee month of birth")
        labelMOB.grid(row=6, column=0)
        labelYOB = tk.Label(self, text="Employee year of birth")
        labelYOB.grid(row=7, column=0)
        labelHealthCare = tk.Label(self, text="Health Care (yes or no)")
        labelHealthCare.grid(row=8, column=0)
        labelHealthCareID = tk.Label(self, text="Employee health care id")
        labelHealthCareID.grid(row=9, column=0)
        labelEmployeeID = tk.Label(self, text="Employee id")
        labelEmployeeID.grid(row=10, column=0)

        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["first_name"])
        userEntry.grid(row=1, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["last_name"])
        userEntry.grid(row=2, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["age"])
        userEntry.grid(row=3, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["address"])
        userEntry.grid(row=4, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["day_of_birth"])
        userEntry.grid(row=5, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["month_of_birth"])
        userEntry.grid(row=6, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["year_of_birth"])
        userEntry.grid(row=7, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["health_care"])
        userEntry.grid(row=8, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["health_care_id"])
        userEntry.grid(row=9, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["employee_id"])
        userEntry.grid(row=10, column=1)

        nextButton = tk.Button(self, text='Next', command=lambda: controller.raise_frame(addEmpFrame1))
        nextButton.grid(row=12, column=1)

        retButton = tk.Button(self, text='Main Menu', command=lambda: controller.raise_frame(mainMenuPage))
        retButton.grid(row=12, column=0)


class addEmpFrame1(tk.Frame): #second registration page, button NEXT moves to the next registration page
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.controller = controller

        empInfo2Label = tk.Label(self, text='Please enter Insurance information.')
        empInfo2Label.grid(row=0, column=1)

        labelMarried = tk.Label(self, text="Married? (yes or no)")
        labelMarried.grid(row=1, column=0)
        labelhInsurance = tk.Label(self, text="Health Care Insurance company")
        labelhInsurance.grid(row=2, column=0)
        labeldInsurance = tk.Label(self, text="Dental Care Insurance company")
        labeldInsurance.grid(row=3, column=0)
        labeloInsurance = tk.Label(self, text="Optical Care Insurance company")
        labeloInsurance.grid(row=4, column=0)
        labelhTier = tk.Label(self, text="hTier")
        labelhTier.grid(row=5, column=0)

        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["married"])
        userEntry.grid(row=1, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["hInsurance"])
        userEntry.grid(row=2, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["dInsurance"])
        userEntry.grid(row=3, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["oInsurance"])
        userEntry.grid(row=4, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["hTier"])
        userEntry.grid(row=5, column=1)

        nextButton = tk.Button(self, text='Next', command=lambda: controller.raise_frame(addEmpFrame2))
        nextButton.grid(row=7, column=1)

        retButton = tk.Button(self, text='Main Menu', command=lambda: controller.raise_frame(mainMenuPage))
        retButton.grid(row=7, column=0)


class addEmpFrame2(tk.Frame): #Final registration page, SUBMIT checks if exists in db, if not, Inserts
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.controller = controller

        empInfo3Label = tk.Label(self, text='Please enter Financial information.')
        empInfo3Label.grid(row=0, column=1)

        label401k = tk.Label(self, text="401k (yes or no)")
        label401k.grid(row=1, column=0)
        labelkContribution = tk.Label(self, text="kContribution")
        labelkContribution.grid(row=2, column=0)
        labelPension = tk.Label(self, text="Pension (yes or no)")
        labelPension.grid(row=3, column=0)
        labelUnionDues = tk.Label(self, text="Union dues (yes or no)")
        labelUnionDues.grid(row=4, column=0)
        labelPayType = tk.Label(self, text="Pay type")
        labelPayType.grid(row=5, column=0)
        labelPayAmount = tk.Label(self, text="Pay amount")
        labelPayAmount.grid(row=6, column=0)

        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["four01k"])
        userEntry.grid(row=1, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["kContribution"])
        userEntry.grid(row=2, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["pension"])
        userEntry.grid(row=3, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["unionDues"])
        userEntry.grid(row=4, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["payType"])
        userEntry.grid(row=5, column=1)
        userEntry = tk.Entry(self, textvariable=self.controller.shared_data["payAmount"])
        userEntry.grid(row=6, column=1)

        submitButton = tk.Button(self, text='Submit', command=lambda: self.addEmployee(controller))
        submitButton.grid(row=8, column=1)

        retButton = tk.Button(self, text='Main Menu', command=lambda: controller.raise_frame(mainMenuPage))
        retButton.grid(row=8, column=0)

    def addEmployee(self, controller): #Checking and inserting function

        temp_stat = 0

        firstName = self.controller.shared_data["first_name"].get()
        lastName = self.controller.shared_data["last_name"].get()
        aGe = self.controller.shared_data["age"].get()
        addRess = self.controller.shared_data["address"].get()
        DOB = self.controller.shared_data["day_of_birth"].get()
        MOB = self.controller.shared_data["month_of_birth"].get()
        YOB = self.controller.shared_data["year_of_birth"].get()
        healthCare = self.controller.shared_data["health_care"].get()
        healthCareID = self.controller.shared_data["health_care_id"].get()
        employeeID = self.controller.shared_data["employee_id"].get()
        marry = self.controller.shared_data["married"].get()
        healthIns = self.controller.shared_data["hInsurance"].get()
        dentalIns = self.controller.shared_data["dInsurance"].get()
        opticalIns = self.controller.shared_data["oInsurance"].get()
        healthTier = self.controller.shared_data["hTier"].get()
        Four1k = self.controller.shared_data["four01k"].get()
        keyContribution = self.controller.shared_data["kContribution"].get()
        penSion = self.controller.shared_data["pension"].get()
        unionDues = self.controller.shared_data["unionDues"].get()
        payType = self.controller.shared_data["payType"].get()
        payAmount = self.controller.shared_data["payAmount"].get()

        attempt = Employee.Register(firstName, lastName, aGe, addRess, DOB, MOB, YOB,
                                    healthCare, healthCareID, employeeID, marry, healthIns,
                                    dentalIns, opticalIns, healthTier, Four1k, keyContribution,
                                    penSion, unionDues, payType, payAmount)
        temp_stat = attempt.databaseInsert()

        if(temp_stat == 1):
            messagebox.showinfo("Status", "Successfully Added")
            controller.raise_frame(mainMenuPage)
            controller.update_frame(mainMenuPage)

        elif(temp_stat == 0):
            messagebox.showinfo("Status", "User Already Exists")
            controller.raise_frame(addEmpFrame)


class removeEmpFrame(tk.Frame): #Under construction
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        retButton = tk.Button(self, text='Main Menu', command=lambda: controller.raise_frame(mainMenuPage))
        retButton.grid(row=12, column=0)


class EmpLookupFrame(tk.Frame): #Under Construction
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        retButton = tk.Button(self, text='Main Menu', command=lambda: controller.raise_frame(mainMenuPage))
        retButton.grid(row=12, column=0)


class calcPayRollFrame(tk.Frame): #Under construction
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        retButton = tk.Button(self, text='Main Menu', command=lambda: controller.raise_frame(mainMenuPage))
        retButton.grid(row=12, column=0)


if __name__ == "__main__":
    gui = GUI()
    gui.mainloop()

編輯:我知道批量代碼很長的閱讀時間,但是我確實沒有這個問題的具體位置,相反,如果您看一下任何Frame的任何類,那么我在邏輯上缺少什么來獲取Frames在使用它們時進行更新/刷新。 先感謝您

每次單擊添加新員工按鈕時,您將需要清除字典值。

一種實現方法是在GUI類中添加一個方法,該方法具有for循環,可將所有值設置為空字符串。

然后,您只需在將框架添加到lambda語句中以提升框架之前,就調用該方法。

因此,將此方法添加到GUI類。

def clear_shared_data(self):
    for key, value in self.shared_data.items():
        print(value.get())
        value.set("")

然后,編輯'Add Employee'按鈕以使用以下命令。

command=lambda: (controller.clear_shared_data(), controller.raise_frame(addEmpFrame))

這將在升起框之前清除字典中的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM