项目帮助,涉及tkinter

aoyhnmkz  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(229)

我试图让tkinter能够找到我输入到gui中的一些服务的总成本。我还不能在函数“myclicker”中得到实际的计算结果,从而将任何值返回到屏幕。寻找一些帮助,我可以得到这个代码采取的输入和使用他们的计算。我也写了很多笔记来帮助别人。这是我的第二篇博文,请放轻松,谢谢!

import tkinter

service = {             #This is the dictionary that holds all of the services and their associated prices
    'Mergers and Acquisitions':3000,
    'Business Valuations':2000,
    'Financial Analysis & Operational Ideas':5000,
    'Strategic Planning Services':3500,
    'Specialized Strategic Consultion Services':4000,
    'Litigation Support':6000,
    '': 0
    }

services = [            #This is the list that holds all of the services (Used for the GUI output)
    '',
    'Mergers and Acquisitions',
    'Business Valuations',
    'Financial Analysis & Operational Ideas',
    'Strategic Planning Services',
    'Specialized Strategic Consultion Services',
    'Litigation Support'
    ]

window = tkinter.Tk()               #Creates the window (GUI)

class QuotaCalc:

    ## A class that asks for data about a client and then calculates
    ## both the time required for the service and the total estimate cost

    def __init__(self, main, cust_name = 'none', co_size = 0, option1=None, option2=None, option3=None):      ##This initializes the class with all of the variables that we will use

        self.co_name = tkinter.Label(main, text = 'Customer/Company Name', font=('Arial Narrow', 20)).grid(row=20, column=1)       #This displays text, the font is the font, and this tells the program what to display
        self.co_name_input = tkinter.Entry(main).grid(row=20, column=3)      #Allows user to input information       #by putting both on row 0, it alligns the text

# can add in blank lables to space out the boxes (reduce the font to something small) on the GUI

        clicked = tkinter.StringVar()           #initalizing "clicked" as a string variable
        clicked2 = tkinter.StringVar()
        clicked3 = tkinter.StringVar()

        clicked.set(services[0])                #Text to be displayed on the menu dropdown
        clicked2.set(services[0])
        clicked3.set(services[0])

        timeRequired = 0                        #Initializing the variable timeRequired

        comp_size_input = tkinter.IntVar()      #Initializing the variable comp_size_input, to be called later in the myClicker function for the calculation

        self.co_size = tkinter.Label(main, text = 'Company Size', font=('Arial Narrow', 20)).grid(row=40, column=1)     #Company Size Label 
        self.comp_size_input = tkinter.Entry(main)                                                                      #Company Size Input Box
        self.comp_size_input.grid(row=40, column=3)                                                                     #Packing the Company Size Label

        self.option_1 = tkinter.Label(main, text = 'Service 1 Needed', font=('Arial Narrow', 20)).grid(row=60, column=1)    #Service Label
        drop = tkinter.StringVar()                                                                                          #Initalizing the variable drop (for the drop box input)
        self.drop = tkinter.OptionMenu( main , clicked , *service )                                                         #DropBox Entry Options
        self.drop.grid(row = 60, column = 3)                                                                                #packs the variable drop to the screen at the grid coordinates
        #dropped = tkinter.StringVar(drop)      Done in the myClicker function

        self.option_2 = tkinter.Label(main, text = 'Service 2 Needed', font=('Arial Narrow', 20)).grid(row=80, column=1)    #Service 2 Label
        drop2 = tkinter.StringVar()                                                                                         #Initalizing the variable drop2 (for the drop box input)
        self.drop2 = tkinter.OptionMenu( main , clicked2 , *service )                                                       #DropBox Entry Options
        self.drop2.grid(row = 80, column = 3)                                                                               #packs the variable drop2 to the screen at the grid coordinates
        #dropped2 = tkinter.StringVar(drop2)

        self.option_3 = tkinter.Label(main, text = 'Service 3 Needed', font=('Arial Narrow', 20)).grid(row=100, column=1)   #Service 3 Label
        drop3 = tkinter.StringVar()                                                                                         #Initalizing the variable drop3 (for the drop box input)
        self.drop3 = tkinter.OptionMenu( main , clicked3 , *service )                                                       #DropBox Entry Options    
        self.drop3.grid(row = 100, column = 3)                                                                              #packs the variable drop3 to the screen at the grid coordinates    
        #dropped3 = tkinter.StringVar(drop3)

        self.bt = tkinter.Button(main, text='Calculate', command = self.myClick, fg = "purple", bg = "light blue").grid(row=120, column=2)     #Creates the Calculate button to run the code that finds the total cost and time required    ##fg is foreground (color), bg is background (color)
        #Need to convert to when the button presses, it runs other functions of the class

        time_req = tkinter.Label(window, text = 'Time Required', font=('Arial Narrow', 20)).grid(row=140, column=1)                     #Creates the label Time Required to describe the output

        total_cost = tkinter.Label(window, text = 'Price Quote', font=('Arial Narrow', 20)).grid(row=160, column=1)                     #Creates the label Total Cost to describe the output

# To fix the calcuation problem, maybe make a boolean to see if the button has been clicked and set it to false, when the boolean becomes true run the functions that do the math?

    def myClick(self):                              #A function that activates once the button has been clicked and is desigend to calculate the total cost and time required for the services and output it to the GUI

        comp_size = self.comp_size_input.get()      #Initalizes the variable copm_size to be used in the time required calcuation
        comp_size = int(comp_size)                  #Converts the variable comp size into an int

        drop = str(self.drop)                       #Initializes and converts the chosen options for services 1, 2, and 3 into a string so they can be used to look up the prices in the service dictionary
        drop2 = str(self.drop2)
        drop3 = str(self.drop3)

        timeRequired = 0
        cost = 0

        if comp_size == 0:                          #This determines how much time will be necessary based on the size of the company
            self.timeRequired = 0                   #Need to add data validation for the company size
        elif comp_size <= 20:
            self.timeRequired = 1
        elif comp_size <= 40:
            self.timeRequired = 2
        elif comp_size <= 60:
            self.timeRequired = 3
        elif comp_size <= 80:
            self.timeRequired = 4
        elif comp_size <= 100:
            self.timeRequired = 5
        elif comp_size <= 150:
            self.timeRequired = 6
        else:
            self.timeRequired = 8

        cost = timeRequired * service[drop]                 #This section is used to determine the total costs based off of the services and the amount of time for the all the services
        if self.drop2 != '':
            cost += self.timeRequired * service[drop2]
        if self.drop3 != '':
            cost += self.timeRequired * service[drop3]

        myLabel = tkinter.Label(window,text = timeRequired)     #Designed to show the total time required and the total cost outputted on the GUI screen
        myLabel.grid(row=140, column=3)
        myLabel2 = tkinter.Label(window, text = cost)
        myLabel2.grid(row=160, column=3)

logo = tkinter.PhotoImage(file=r"C:\Users\brian\OneDrive\Documents\TCU\Junior Year\Second Semester\Business Information System Development INSC 30833\Bar Ad Pic.PNG")

## YOU MUST USE THE FILE PATH TO THE LOGO ON YOUR OWN COMPUTER

## THIS SHOWS MY PERSONAL FILE PATH

w1 = tkinter.Label(window, image=logo).grid(row=0, column = 2)          #Displays the picture at this grid coordinate

window.title('Barrington Advisory Quota Calculator')        #Window Title
window.geometry('1000x500')         #Sets the size of the window

# window.configure(bg='light blue') <- If we want to change the color of the background

e = QuotaCalc(window)

window.mainloop()       #Tells the program to continue running until the GUI is closed
rbl8hiat

rbl8hiat1#

注意:下面的代码可以由op和其他任何人使用,只要稍加调整。
选项,如注解中的选项(如matiiss关于使用 StringVar() ,我在这里使用)可能对您更有帮助,但我会这样做(有很多方法,但我选择了这一种):

import tkinter
    from tkinter import ttk # This is to import *most* of the elements you need for a decent-ish GUI w/o calling "tkinter" then elemtent name. I do this because I am lazy

    # Setting up the GUI
    window = tkinter.Tk()
    window.title('Barrington Advisory Quota Calculator')                    # Window Title
    window.geometry('500x500')                                              # Sets the size of the window. Edit this to suit you. I am gonna put  500x500 because I am fine with it
    #window.configure(bg='light blue')                                      # If we want to change the color of the background (optional)
    window.resizable(False, False)                                          # Make sure that the current user cannot resize the window, keeping it at a fixed size

    # Some variables that are kinda important to OP's project (OP, uncomment the line below)
    # logo = tkinter.PhotoImage(file=r"C:\Users\brian\OneDrive\Documents\TCU\Junior Year\Second Semester\Business Information System Development INSC 30833\Bar Ad Pic.PNG")
    currentSelected = tkinter.StringVar()                                   # Kind of like doing 'currentSelected = ""' but with a bit of a special use later

    # Functions
    def fetch():
        localCurSel = currentSelected.get()                                 # Local variable to keep things easy imo

        # BIG DISCLAIMER:
        # I have no idea what is going on with the program OP is trying to make for a project
        # as I am very new to Python (~4 months)

        # Everything after the last line of this function can be expanded to OP's or anyone's
        # needs. So if you wanna do some fancy stuff with it, go ahead. What's next is how to display
        # the value from this function

        leaveMeEmpty.configure(text="Output: {0}".format(localCurSel))      # This is how you display the output of the function

    # I don't really get the "self" parameter much, so let's do this on how I'd write this
    # GUI Variables
    # NOTE: ALWAYS put functions ahead of GUI variables ESPECIALLY when calling a function with a variable
    intrLabl = ttk.Label(window, text="Barrington Advisory Quota Calculator")
    serviceList = ttk.Combobox(window, textvariable=currentSelected, width=50)
    serviceList["values"] = (            # This is the list that holds all of the services for the combobox
        '',
        'Mergers and Acquisitions',
        'Business Valuations',
        'Financial Analysis & Operational Ideas',
        'Strategic Planning Services',
        'Specialized Strategic Consultion Services',
        'Litigation Support'
    )
    serviceCalcul8 = ttk.Button(window, text="Calculate the ", command=fetch)

    leaveMeEmpty = ttk.Label(window, text="Output: ")                       # Variable kinda empty, eh? This is where I-can't-Explain-Further-than-This-because-I-am-a-noob-land begins

    # Combobox configs
    serviceList["state"] = "readonly"                                       # Make sure that the user cannot change what's inside the combobox except for the ones only in line 19

    # Placing the elements/GUI parts thingy
    intrLabl.pack()
    serviceList.pack(padx=10, pady=10)
    serviceCalcul8.pack(padx=10)
    leaveMeEmpty.pack(padx=10)

    window.mainloop()

我记录了它/用注解填充了它,因为它可以帮助人们理解一行中发生了什么,例如

相关问题