Parallel Resistance Calculator GUI (Python)

vegaseat 2 Tallied Votes 3K Views Share

While the calculation of the total resistance of two resistors in parallel is simple, this code shows you how to trap a number of potential errors that come with the entry of the required data. All is wrapped easily into a colorful GUI program, due to the simplicity of the Tkinter module. The GUI contains two data entry boxes, two labels for user instructions, one label to show the calculated results, and a button to start the calculation defined in the function. This could easily be a GUI template for other calculations that need two data inputs. Remember that Tkinter works with Windows, Linux and the Mac OS-X.

# a GUI program to calculate the parallel resistance of two resistors using Tkinter
# tested with Python24      vegaseat      22jul2005

from Tkinter import *

def calculate():
    """ calculate the resistance of two resistors in parallel """
        r1 = float(enter1.get())
        r2 = float(enter2.get())
        if r1 + r2 > 0:
            rp = (r1 * r2) / (r1 + r2)
            label3.config(text='Parallel resistance = '+ str(rp))
            label3.config(text='division by zero error')
    except ValueError:
        label3.config(text='Enter numeric values for r1 and r2')

def setfocus2(dummy):

# create root window
root = Tk()
# create all the components
label1 = Label(root, text='Enter value of resistor1:', width=28)
enter1 = Entry(root, bg='yellow')
label2 = Label(root, text='Enter value of resistor2:')
enter2 = Entry(root, bg='yellow')
btn1 = Button(root, text='Calculate', command=calculate)
label3 = Label(root, text='', bg='green')
# pack the root window in that order
label1.pack(side=TOP, fill=X)
enter1.pack(side=TOP, fill=X)
label2.pack(side=TOP, fill=X)
enter2.pack(side=TOP, fill=X)
label3.pack(side=TOP, fill=X)
# cursor in enter1
# return key in enter1 sets focus to enter2
enter1.bind("<Return>", func=setfocus2)
# start event loop and program
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.