I have a homework assignment that I almost have completed, but the scrollbar does not function as expected. While it works when I'm focused on the Text, it does not work when I try to move the scrollbar or use the arrows.
from tkinter import *
class LoanCalculator:
def __init__(self):
window = Tk()
window.title("Loan Calculator")
frame = Frame(window)
frame.pack()
Label(frame, text="Loan Amount").grid(row=1,column=1, sticky=W)
self.loanAmmount = StringVar()
self.entryLoan = Entry(frame, textvariable=self.loanAmmount, justify=RIGHT)
Label(frame, text="Years").grid(row=1, column=3,sticky=W)
self.years = StringVar()
self.entryYears = Entry(frame, textvariable=self.years, justify=RIGHT)
btCalc = Button(frame, text="Calculate Loan", command=self.Calculate)
scrollbar = Scrollbar(frame)
self.text = Text(frame, width=60, height=10,wrap=WORD, yscrollcommand=scrollbar.set)
self.entryLoan.grid(row=1, column=2)
self.entryYears.grid(row=1, column=4)
btCalc.grid(row=1, column=5)
self.text.grid(row=2,column=1,columnspan=4)
scrollbar.grid(row=2, column=5, sticky="NSW")
window.mainloop()
def Calculate(self):
self.text.delete("1.0", END)
self.text.insert(END, "{0:<20s}{1:<20s}{2:<20s}".format("Interest Rate", "Monthly Payment", "Total Payment"))
aIR = 5.0
mIR = 0
mP = 0
tP = 0
fLA = 0
fYear = 0
lA = 0
year = 0
textToOut = ""
while aIR <= 8.0:
fLA = self.loanAmmount.get()
fYear = self.years.get()
lA = int(fLA)
year = int(fYear)
mIR = aIR / 1200
mP = lA * mIR / (1 - (pow(1 / (1 + mIR), year * 12)))
tP = mP * year * 12
textToOut = format(aIR, ">5.3f") + "%" + format(mP, "20.2f") + format(tP, "20.2f") + "\n"
self.text.insert(END, textToOut)
aIR += 1.0 / 8
LoanCalculator()
EDIT
I've changed my question to drop the text portion, as I have figured a workaround for that.
You need to configure the scrollbar to run an action (update the view of the text area) on scrolling. Add this line of code after you defined your text area.
scrollbar.config(command=self.text.yview)
So the code block of __init__ would be something like this:
def __init__(self):
window = Tk()
window.title("Loan Calculator")
frame = Frame(window)
frame.pack()
Label(frame, text="Loan Amount").grid(row=1,column=1, sticky=W)
self.loanAmmount = StringVar()
self.entryLoan = Entry(frame, textvariable=self.loanAmmount, justify=RIGHT)
Label(frame, text="Years").grid(row=1, column=3,sticky=W)
self.years = StringVar()
self.entryYears = Entry(frame, textvariable=self.years, justify=RIGHT)
btCalc = Button(frame, text="Calculate Loan", command=self.Calculate)
scrollbar = Scrollbar(frame)
self.text = Text(frame, width=60, height=10,wrap=WORD, yscrollcommand=scrollbar.set)
scrollbar.config(command=self.text.yview)
self.entryLoan.grid(row=1, column=2)
self.entryYears.grid(row=1, column=4)
btCalc.grid(row=1, column=5)
self.text.grid(row=2,column=1,columnspan=4)
scrollbar.grid(row=2, column=5, sticky="NSW")
Related
i am new to programming and i am programming my first project and i want to know can i do a calculation in two text boxes and get the result to another one
And thank you guys
Here is my code:
from Tkinter import *
import Tkinter as tk
def add(x, y):
return x+y
root = tk.Tk()
root.geometry('340x275+50+50')
root.title('Calculator')
root.resizable(True, True)
root.iconbitmap("C://123//
icon.ico")
num_1 = Label(root,
text="First number :")
num_1.grid(row=1, column=1)
num_2 = Label(root,
text="Second number :")
num_2.grid(row=1, column=3)
textBox1 = Text(root,
height=2, width=10)
textBox1.grid(row=1, column=2)
input1 = textBox1.get("1.0",
END)
textBox2 = Text(root,
height=2, width=10)
textBox2.grid(row=1, column=4)
input2 = textBox2.get("1.0",
END)
textBox_result = Text(root,
height=2, width=40)
textBox_result.grid(row=3,
column=2)
btn_add = Button(root,
text="+", command=add(input1,
input2))
btn_add.grid(row=2, column=1)
root.mainloop()
As newbie tutorial. Try this;
from tkinter import *
root = Tk()
root.title("Sum Two Numbers With GUI Using Python Source Code")
width = 400
height = 280
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)
#==============================METHODS========================================
def calculate():
if not num1.get() and not num2.get():
print("Please enter a number")
else:
res=int(num1.get())+int(num2.get())
lbl_text.config(text = "The answer is %d" % (res))
num1.set=""
num2.set=""
#==============================FRAMES=========================================
Top = Frame(root, bd=2, relief=RIDGE)
Top.pack(side=TOP, fill=X)
Form = Frame(root, height=200)
Form.pack(side=TOP, pady=20)
#==============================LABELS=========================================
lbl_title = Label(Top, text = "Sum Two Numbers With GUI Using Python Source Code", font=('arial', 12))
lbl_title.pack(fill=X)
lbl_num1 = Label(Form, text = "Number 1:", font=('arial', 14), bd=15)
lbl_num1.grid(row=0, sticky="e")
lbl_num2 = Label(Form, text = "Number 2:", font=('arial', 14), bd=15)
lbl_num2.grid(row=1, sticky="e")
lbl_text = Label(Form)
lbl_text.grid(row=2, columnspan=2)
#==============================ENTRY WIDGETS==================================
num1 = Entry(Form, font=(14))
num1.grid(row=0, column=1)
num2 = Entry(Form, font=(14))
num2.grid(row=1, column=1)
#==============================BUTTON WIDGETS=================================
btn_calculate = Button(Form, text="Calculate", width=45, command=calculate)
btn_calculate.grid(pady=25, row=3, columnspan=2)
Another one easy for you.
import tkinter as tk
from functools import partial
def findsum(l3, num1, num2):
n1 = int(num1.get())
n2 = int(num2.get())
n3 = n1 + n2
l3.config(text="Result = %d" % n3)
return
root = tk.Tk()
root.title("Xiith.com")
root.geometry("700x500")
number1 = tk.StringVar()
number2 = tk.StringVar()
l1 = tk.Label(root, text="Enter 1st number").place(x=20, y=60)
l2 = tk.Label(root, text="Enter 2nd number").place(x=20, y=120)
t1 = tk.Entry(root, textvariable=number1).place(x=200, y=60)
t2 = tk.Entry(root, textvariable=number2).place(x=200, y=120)
labelResult = tk.Label(root)
labelResult.place(x=250, y=200)
findsum = partial(findsum, labelResult, number1, number2)
b1 = tk.Button(root, text="ADD", command=findsum).place(x=200, y=300)
b2 = tk.Button(root, text="Cancel", command=root.destroy).place(x=250, y=300)
root.mainloop()
for one of my first little projects I coded a fitnesscalculator last evening. Which has 3 functionalities at the start: Calculating the 1RM, BMI and FFMI. I'm running into the problem of overlapping labels when I first calculate the 1RM and then the FFMI. I have already googled and looked for similar threads but I couldn't find an answer to my solutions as my Gui is and its functionalities are based around a combobox. Please excuse the rather messy code, but I have already tried several methods to deal with this problem
from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk
root = Tk()
root.geometry("400x400")
root.title("Fitness Calculator")
#dropdown
Options = ["1RM Calculator", "BMI Calculator", "FFMI Calculator"]
#functions
def picker(input):
global calculate_button
global bf_box
global bf_label
global result_label
global result2_label
global result3_label
calculate_button.destroy()
result_label.pack_forget()
result2_label.destroy()
result3_label.destroy()
bf_label.destroy()
bf_box.destroy()
selected = drop.get() #holt sich wert vom dropdown
####################RM CALCULATOR####################
if selected == Options[0]:
#labels
weight_label = Label(root,text="Enter your training weight here: ", padx=10, pady=10)
weight_label.grid(row=2, column=0, sticky=W)
reps_label = Label(root,text="Enter your repetitions here: ", padx=10)
reps_label.grid(row=3, column=0, sticky=W)
def calculate():
weight = int(weight_box.get())
reps = int(reps_box.get())
one_rm = round(weight*(36/(37-reps)), 2)
#Result
result_label = Label(root, text="Your 1RM is: " + str(one_rm) + " kg")
result_label.grid(row=4)
weight_box.delete(0,END)
reps_box.delete(0,END)
#Entryfields
weight_box = Entry(root)
weight_box.grid(row=2, column=1)
reps_box = Entry(root)
reps_box.grid(row=3, column=1)
#Calculate button
calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
calculate_button.grid(row=4,column=1,pady=10)
####################BMI CALC####################
if selected == Options[1]:
#LABELS
weight_label = Label(root,text="Enter your weight in kg here: ", padx=10, pady=10)
weight_label.grid(row=2, column=0, sticky=W)
height_label = Label(root,text="Enter your height in cm here: ", padx=10)
height_label.grid(row=3, column=0, sticky=W)
#ENTRY BOXES
weight_box = Entry(root)
weight_box.grid(row=2, column=1)
height_box = Entry(root)
height_box.grid(row=3, column=1)
def calculate():
weight = float(weight_box.get())
height = float(height_box.get())/100
bmi = round(weight/(height**2),0)
#Result
result_label = Label(root, text="Your BMI is: " + str(bmi))
result_label.grid(row=4)
weight_box.delete(0,END)
height_box.delete(0,END)
#Calculate button
calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
calculate_button.grid(row=4,column=1,pady=10)
####################FFMI####################
if selected == Options[2]:
calculate_button.destroy()
#LABELS
weight_label = Label(root,text="Enter your weight in kg here: ", padx=10,pady=5)
weight_label.grid(row=2, column=0, sticky=W)
height_label = Label(root,text="Enter your height in cm here: ", padx=10,pady=5)
height_label.grid(row=3, column=0, sticky=W)
bf_label = Label(root,text="Enter your estimated bodyfat % here: ", padx=10,pady=5)
bf_label.grid(row=4, column=0, sticky=W)
#ENTRY BOXES
weight_box = Entry(root)
weight_box.grid(row=2, column=1)
height_box = Entry(root)
height_box.grid(row=3, column=1)
bf_box = Entry(root)
bf_box.grid(row=4, column=1)
def calculate():
weight = float(weight_box.get())
height = float(height_box.get())/100
bf = float(bf_box.get())
total_bf = weight*(bf)
lean_weight = weight*(1-(bf/100))
ffmi = round((lean_weight/height**2),2)
adjusted_ffmi = ffmi + 6.1 * (1.8 - height)
#Result
result_label = Label(root, text="Lean Mass: " + str(lean_weight) + " kg")
result_label.grid(row=6, sticky=W, padx=5)
result_label2 = Label(root, text="FFMI: " + str(ffmi))
result_label2.grid(row=7, sticky=W, padx=5)
result_label3 = Label(root, text="adjusted-FFMI: " + str(adjusted_ffmi))
result_label3.grid(row=8,sticky=W, padx=5)
weight_box.delete(0,END)
height_box.delete(0,END)
bf_box.delete(0,END)
#Calculate button
calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
calculate_button.grid(row=5,column=1,pady=10)
calculate_button = Button(root,text="Calculate", width=16 )
calculate_button.grid(row=4,column=1,pady=10)
calculate_button.destroy()
#Dropdownbox
drop = ttk.Combobox(root, value=Options, state="readonly")
drop.current(0)
drop.grid(row=0)
drop.bind("<<ComboboxSelected>>", picker)
result_label = Label(root,text="test")
result_label.grid(row=4)
result2_label = Label(root,text="")
result2_label.grid(row=4)
result3_label = Label(root,text="")
result3_label.grid(row=4)
bf_label = Label(root)
bf_box = Entry(root)
picker(drop.current(0))
root.mainloop()
Here a Screenshot of the problem I'm referencing to:
You keep creating a new Label with name result_label in your calculate methods.
This piles the labels on top of each other, since the result_label.destroy() does not remove them from the grid.
Instead of destroying them, keep just one instance (which you already defined global) and then configure them with the new text:
result_label.config(text="Your BMI is: " + str(bmi))
I've made a simple GUI for placing objects in RoboDK via a Python script using Tkinter.
Essentailly, the user selects an object using the btnSelect button, which then updates the entry widgets with its coordinates (x, y, z, then Euler rotation). The user can then edit the entry widgets then select the "Move object" button (or btnMove in the code) to move the object to the new position. However, when selecting an object for the second time, the entry fields cannot be edited without selecting a new object.
from tkinter.constants import DISABLED, NORMAL, CENTER, END
from typing import *
import tkinter as tk
import threading
from robolink import * # RoboDK API
from robodk import * # Robot toolbox
X_MAX = 500
X_MIN = 0
Y_MAX = 300
Y_MIN = -360
ROTZ_MAX = 180
ROTZ_MIN = -180
# Keep track of selected item
obj = None
def main():
rdk = Robolink()
window = buildGUI(rdk)
window.mainloop()
def buildGUI(rdk: Robolink) -> tk.Tk:
window = tk.Tk()
canvas = tk.Canvas(window, width=200)
canvas.grid(columnspan=3, rowspan=14)
# Set the window title (must be unique for the docking to work, try to be creative)
window_title = 'Move object window'
window.title(window_title)
title = tk.Label(window, text="Move Object", font="none 14 bold")
title.grid(columnspan=3, column=0, row=0)
# Delete the window when we close it
window.protocol("WM_DELETE_WINDOW", lambda: onClose(window))
deadspace1 = tk.Label(text="")
deadspace1.grid(columnspan=3, column=0, row=1)
selectText = tk.StringVar()
btnSelect = tk.Button(window, textvariable=selectText, height=2, width=0,
bg="#bbbbbb", fg='white', justify=CENTER)
selectText.set("Select object")
btnSelect.grid(column=1, row=2)
deadspace2 = tk.Label("")
deadspace2.grid(columnspan=3, column=0, row=3)
objName = tk.StringVar()
objLabel = tk.Label(window, textvariable=objName, font="none 12 bold")
objName.set("None Selected")
objLabel.grid(columnspan=3, column=0, row=4)
deadspace2 = tk.Label("")
deadspace2.grid(columnspan=3, column=0, row=5)
# Position options
xLabel = tk.Label(window, text="x: ", font='none 12')
xLabel.grid(column=0, row=6)
xEntry = tk.Entry(window, width=10)
xEntry.grid(columnspan=2, column=1, row=6)
yLabel = tk.Label(window, text="y: ", font='none 12')
yLabel.grid(column=0, row=7)
yEntry = tk.Entry(window, width=10)
yEntry.grid(columnspan=2, column=1, row=7)
zLabel = tk.Label(window, text="z: ", font='none 12')
zLabel.grid(column=0, row=8)
zEntry = tk.Entry(window, width=10)
zEntry.grid(columnspan=2, column=1, row=8)
# Rotation options
rxLabel = tk.Label(window, text="rx: ", font='none 12')
rxLabel.grid(column=0, row=9)
rxEntry = tk.Entry(window, width=10)
rxEntry.grid(columnspan=2, column=1, row=9)
ryLabel = tk.Label(window, text="ry: ", font='none 12')
ryLabel.grid(column=0, row=10)
ryEntry = tk.Entry(window, width=10)
ryEntry.grid(columnspan=2, column=1, row=10)
rzLabel = tk.Label(window, text="rz: ", font='none 12')
rzLabel.grid(column=0, row=11)
rzEntry = tk.Entry(window, width=10)
rzEntry.grid(columnspan=2, column=1, row=11)
entries = [xEntry, yEntry, zEntry, rzEntry, ryEntry, rxEntry]
deadspace3 = tk.Label(text="")
deadspace3.grid(columnspan=3, column=0, row=12)
btnMove = tk.Button(window, text="Move object", height=2, width=0,
bg="#bbbbbb", fg='white', justify=CENTER,
command=lambda: moveObject(entries))
btnMove.grid(column=1, row=13)
selectCallback = lambda: select_item(rdk, selectText, objName, entries)
btnSelect['command'] = selectCallback
EmbedWindow(window_title)
return window
# Close the window
def onClose(window: tk.Tk):
window.destroy()
quit(0)
def select_item(rdk: Robolink, selectText: tk.StringVar, objName: tk.Label,
entries: List[tk.Entry]):
def thread_btnSelect():
selectText.set("Waiting...")
item = rdk.ItemUserPick('Select an item', ITEM_TYPE_OBJECT)
if item.Valid():
global obj
obj = item
objName.set(item.Name())
updateObjectPosition(item, entries)
selectText.set("Select object")
# Prevent RoboDK from freezing
threading.Thread(target=thread_btnSelect).start()
def updateObjectPosition(item: Item, entries: List[tk.Entry]):
pose = item.Pose()
coords = Pose_2_KUKA(pose)
for entry, coord in zip(entries, coords):
entry.delete(0, END)
entry.insert(0, str(coord))
def moveObject(entries: tk.Entry):
global obj
if obj is None:
ShowMessage("No object selected")
return
try:
coords = getCoords(entries)
obj.setPose(KUKA_2_Pose(coords))
except Exception as err:
ShowMessage(str(err))
def getCoords(entries: List[tk.Entry]) -> list:
coords = [0] * 6
for i, entry in enumerate(entries):
coords[i] = float(entry.get())
return coords
if __name__ == "__main__":
main()
Using a tkinter.Variable such as tkinter.DoubleVar with your entries should fix this issue. You can also use tkinter.DoubleSpin for convenience.
x, y, z, rx, ry, rz = Pose_2_TxyzRxyz(item.Pose())
xVar = tk.DoubleVar(value=x)
xEntry = tk.Spinbox(window, textvariable=xVar, format="%.2f", from_=-9999999, to=9999999)
xVal = xVal.get()
I am trying to make a staffing calculator using GUI tkinter in python I expect to get the function calculation results once I fill all entries and click on calculate button in a new window (master) based on the entry but unfortunately I got an empty label in the new window also I am not reeving any error to fix, would you please help me?, here is my code and screen shot:
from tkinter import *
root = Tk()
root.title("Workload Staffing Calculator")
#Header
headerlab = Label(root, text="Please fill the below form and click calculate to get the required staff.").grid(row=0,columnspan=2,pady=20,padx=20)
#Inputs names
vollabel = Label(root, text="Volumes").grid(padx=0,pady=10)
ahtlabel = Label(root, text="AHT (sec.)").grid(padx=0, pady=10)
Occlabel = Label(root, text="Occupancy (%)").grid(padx=0, pady=10)
Shrinklabel = Label(root, text="Shrinkage (%)").grid(padx=0, pady=10)
weekendlabel = Label(root, text="Days Off").grid(padx=0, pady=10)
Shiftlabel = Label(root, text="Shift Duration (h)").grid(padx=0, pady=10)
#Entry inptus
volentry = Entry(root, width=10, borderwidth=3)
ahtentry = Entry(root, width=10, borderwidth=3)
occentry = Entry(root, width=10, borderwidth=3)
shrinkentry = Entry(root, width=10, borderwidth=3)
weekendentry = Entry(root, width=10, borderwidth=3)
shiftentry = Entry(root, width=10, borderwidth=3)
#shoving inputs on screen
volentry.grid(row=1, column=1, padx=20)
ahtentry.grid(row=2, column=1, padx=20)
occentry.grid(row=3, column=1, padx=20)
shrinkentry.grid(row=4, column=1, padx=20)
weekendentry.grid(row=5, column=1, padx=20)
shiftentry.grid(row=6, column=1, padx=20)
#Calculate Fuction
def calstaff() :
v = volentry.get()
a = ahtentry.get()
o = occentry.get()
s = shrinkentry.get()
w = weekendentry.get()
sh = shiftentry.get()
required = (int(v) * int(a)) / (int(sh) * 3600)
total = required * (7 / (7 - int(w))) * (1 + float(s))
newwindow = Tk()
newwindow.title("The required is: ")
result = Label(newwindow, textvariable=total).pack()
return result
#calculate button
calculate = Button(root, text="Calculate", command=calstaff)
calculate.grid(padx=20,pady=10)
root.mainloop()
It is not recommended to use Tk() more than once as it can interrupt the flow of the main loop. To create another window you should try using Toplevel()
Secondly, Instead of textvariable use text
Refer to the code below:
.
..
def calstaff() :
v = volentry.get()
a = ahtentry.get()
o = occentry.get()
s = shrinkentry.get()
w = weekendentry.get()
sh = shiftentry.get()
required = (int(v) * int(a)) / (int(sh) * 3600)
total = required * (7 / (7 - int(w))) * (1 + float(s))
newwindow = Toplevel() #TOPLEVEL() USED
newwindow.title("The required is: ")
result = Label(newwindow, text=total) #text instead of textvariable
result.pack()
newwindow.mainloop() #mainloop for newwindow
..
I want to link my radiobuttons with the title, like merge my title with the radio button. This is the code which I implemented:
but1 = Radiobutton(text = "Current",value = 0)
but1.place(x =400,y = 150)
but2 = Radiobutton(text = "Previous",value = 1)
but2.place(x =320,y = 150)
but3 = Radiobutton(text = "Current",value = 2)
but3.place(x =400,y = 260)
but4 = Radiobutton(text = "Previous",value = 3)
but4.place(x =320,y = 260)
the_window.geometry("510x430")
label1 = Label(the_window,text = "Most-Discussed \n TV SHOW", font =
"Times 10 bold")
label1.place(x = 350,y = 110)
label2 = Label(the_window,text = "Most-Discussed \n TV SHOW", font =
"Times 10 bold")
label2.place(x = 350,y = 230)
This is the actual result:
This is the expected result:
I don't know if you know this, but that widget is called a LabelFrame. See the below example.
P.S. I have changed your geometry manager to grid
import tkinter as tk
root = tk.Tk()
f1 = tk.LabelFrame(root, text="Most-Discussed \n TV SHOW", labelanchor="n", font="Verdana 12 bold", bd=4)
f1.grid(row=0, column=0, padx=10, pady=10)
f2 = tk.LabelFrame(root, text="Music Vinyl \n Album Chart", labelanchor="n", font="Verdana 12 bold", bd=4)
f2.grid(row=1, column=0, padx=10, pady=10)
but1 = tk.Radiobutton(f1, text="Current", value = 0)
but1.grid(row=0, column=0)
but2 = tk.Radiobutton(f1, text="Previous" ,value = 1)
but2.grid(row=0, column=1)
but3 = tk.Radiobutton(f2, text="Current", value = 2)
but3.grid(row=0, column=0)
but4 = tk.Radiobutton(f2, text="Previous" ,value = 3)
but4.grid(row=0, column=1)
root.mainloop()