I am creating a Python factorial program, and I have set it up with tkinter to print the number you input to the input box into the Python shell, but how do I instead print it into a separate text box? Here is my code: from tkinter import *
def factorial(n):
first = True
for number in range(1, n+1):
if first:
answer = number
first = False
else:
answer = answer * number
return answer
def callback():
n = int(e.get())
print(factorial(n))
window = Tk()
e = Entry(window)
e.pack()
t = Text()
t.pack()
e.focus_set()
b = Button(window, text="get", width=10, command=callback)
b.pack()
mainloop()
You use the insert method of the text widget:
def callback():
n = int(e.get())
result = factorial(n)
t.insert("1.0", str(result))
Related
I am trying to make a loan amortization table inside tkinter GUI using text box. However, all the loan amortization table is fully displayed in the terminal console as an output.
The tkinter text BOX output display's only the last line: Here is the full code:
import math
import tkinter as tk
from tkinter import *
def calcLoanPayment(p, r, n, t):
if p > 0 and r > 0 and n > 0 and t > 0:
clp = (p *(r/n)*(pow(1 + r/n, n * t)))/(pow(1 + r/n, n * t)-1)
clp = round(clp, 2)
return clp
else:
return -1
def runApp(): #This will bound the function runapp to the calcbtn.
print("running")
p = principalentry.get() #this will get value as a string
try:
p = float(p) #this will make cast it to float variable.
except:
p = -1
principalentry.delete(0, END) #this will clear the entry after calculation
r = interestrateentry.get()
try: #Try will help from crushing the program when wrong value entered
r = float(r)
except:
r = -1
interestrateentry.delete(0, END) #this will clear the entry after calculation
n = compoundintervalentry.get() #this will get value as a string
try:
n = int(n) #this will make cast it to float variable.
except:
n = -1
compoundintervalentry.delete(0, END) #this will clear the entry after calculation
t = durationentry.get()
try: #Try will help from crushing the program when wrong value entered
t = int(t)
except:
t = -1
durationentry.delete(0, END) #this will clear the entry after calculation
clp = calcLoanPayment(p,r,n,t)
print(clp)
paymentinterval = n*t
paymentinterval = int(paymentinterval)
startingBalance=p
endingBalance=p
for i in range(1, paymentinterval+1):
interestcharge =r/n*startingBalance
endingBalance=startingBalance+interestcharge-clp
result ="\t\t"+str(i)+"\t\t" +str(round (startingBalance, 1)
)+"\t\t"+str(round (interestcharge, 1))+"\t\t"+str(round (clp, 1)
)+"\t\t"+str(round (endingBalance, 1))
startingBalance = endingBalance
print(result)
finaloutput = result
output.config(state="normal")
output.delete(0.0, 'end')
output.insert(END, finaloutput)
output.config(state="disabled")
#Frontend maincode Startshere:
#sketch the design of the user interface first.
root = tk.Tk()
root.config(bg="#F8B135")
root.state("zoomed")
#There are 3 steps to build event programming
#Step 1: construct the widgets
#step 2: configure the widget to make it nicer
#srep 3: place or pack the widget in the root window
title = Label(root, text = "Loan Payment Calculator", font = 'bold')
title.config(fg='white', bg="#28348A")
title.pack(fill = BOTH)
principallabel = Label(root, text="Principal: ")
principallabel.config(anchor = W, font = 'bold', bg="#F8B135")
principallabel.place(x=50, y=30)
principalentry = Entry(root)
principalentry.config(bg="#ffffff")
principalentry.place(x=400, y=30)
interestratelabel = Label(root, text="Interest Rate: enter as Decimal (eg.2% as 0.02) ")
interestratelabel.config(anchor = W, font = 'bold', bg="#F8B135")
interestratelabel.place(x=50, y=70)
interestrateentry = Entry(root)
interestrateentry.config(bg="#ffffff")
interestrateentry.place(x=400, y=70)
compoundintervallabel = Label(root, text="Compound Interval: ")
compoundintervallabel.config(anchor = W, font = 'bold', bg="#F8B135")
compoundintervallabel.place(x=50, y=110)
compoundintervalentry = Entry(root)
compoundintervalentry.config(bg="#ffffff")
compoundintervalentry.place(x=400, y=110)
durationlabel = Label(root, text="Duration: ")
durationlabel.config(anchor = W, font = 'bold', bg="#F8B135")
durationlabel.place(x=50, y=150)
durationentry = Entry(root)
durationentry.config(bg="#ffffff")
durationentry.place(x=400, y= 150)
output = Text(root)
output.config(width= 150, height = 100, bg="white", state="disabled", borderwidth=2, relief= "groove", wrap='word')
output.place(x=50, y=230)
calcbtn = Button(root, text= "Calculate", font = 'bold', highlightbackground="#3E4149")
calcbtn.config(fg='#28348A',command=runApp)
calcbtn.place(x=50, y=190)
root. mainloop()
file.close()`
I couldn't figure out How to display the whole output like the terminal did on the tkinter textbox output function. your help is much appreciated.
There are 2 small changes to the code in the function runApp()
output.config(state="normal")
# output.delete(0.0, 'end') # This line deletes the last entry in the text box. Remove this
output.insert(END, finaloutput + '\n') # Add a newline here. Generates the desired 'tabular' output
output.config(state="disabled")
I'm learning to work with Python and Tkinter, so I'm doin this simple calculator app. My main problems come from the function calculator_tasks:
In the first condition, it should be deleting the 0, but it doesn't do it, why is that?
I'm trying to get text when I press the button, but it just prints '/', what's wrong in that?
Please see below the full code, so you might be able to help me.
from tkinter import *
import tkinter as tk
class calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
master.geometry("10x10")
grid_size = 4
a=0
while a <= grid_size:
master.grid_rowconfigure(a,weight=1, uniform='fred')
master.grid_columnconfigure(a,weight=1, uniform='fred')
a += 1
self.ini_frame = Frame(master,bg="light blue",highlightthickness=2, highlightbackground="black")
self.calc_title = Label(self.ini_frame, text ="Calculator",bg="light blue")
self.calculation_frame = Frame(master,bg="black")
self.calculation = IntVar(master,0)
self.calc_figure = Text(self.calculation_frame,fg="white",bg='black')
self.calc_figure.insert(END,0)
self.ini_frame.grid(columnspan=4,sticky=NSEW)
self.calculation_frame.grid(row=1,columnspan=4,sticky=NSEW)
self.calc_title.grid(padx=20)
self.calc_figure.grid(pady=20,padx=20)
master.update_idletasks()
def calculator_tasks():
if self.calc_figure.get("1.0",END) == 0:
self.calc_figure.delete(0,END)
self.calc_figure.insert(END,i)
else:
self.calc_figure.insert(END,i)
r = 2
c = 0
numbers = list(range(10))
numbers.remove(0)
self.calculator_btns=[ ]
for i in numbers:
if c == 2:
self.calculator_btns.append( Button(master, text = i, command = calculator_tasks))
self.calculator_btns[-1].grid(row = r, column = c, pady=20, padx=20,sticky=NSEW)
r += 1
c = 0
else:
self.calculator_btns.append( Button(master, text = i,command=calculator_tasks))
self.calculator_btns[-1].grid(row = r, column = c, pady=20, padx=20,sticky=NSEW)
c += 1
operators = ["+","*","/"]
self.operator_btns =[ ]
r=2
for i in operators:
self.operator_btns.append( Button(master, text = i))
self.operator_btns[-1].grid(row = r, column = 3, pady=20, padx=20,sticky=NSEW)
r += 1
root = Tk()
gui = calculator(root)
root.mainloop()
Here is a simple example:
According to your question: Retrieve text from button created in a loop
import tkinter as tk
root = tk.Tk()
####### Create Button ###############
def get_text(text):
print(text)
for i in range(10):
text = f'Hello I am BeginnerSQL74651 {i}'
button = tk.Button(root, text=text, command=lambda button_text=text: get_text(button_text))
button.grid()
root.mainloop()
I am trying to update information in tkinter labels and buttons without redrawing entire screens. I'm using Python 3, a Raspberry Pi, and Idle. I have a trivial example of what I am trying to do. I see comments here that suggest I need to learn to manipulate stringvariable or IntVar, etc. but my book is totally unhelpful in that regard. In this example, I would like the number between the buttons to track the value of the number as it changes with button pushes.
##MoreOrLess.01.py
from tkinter import *
global number
number = 5
root = Tk()
root.title("Test Buttons")
def Less():
global number
number -= 1
print ("The number is now ", number)
def More():
global number
number += 1
print("The number is now ", number)
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, text = number).pack(pady = 20)
MakeLabel(number)
Not only do you base yourself in a book, check the official documentation of tkinter. in your case you must create a variable of type IntVar with its set() and get() method, and when you want to link that variable through textvariable.
from tkinter import *
root = Tk()
root.title("Test Buttons")
number = IntVar()
number.set(5)
def Less():
number.set(number.get() - 1)
print ("The number is now ", number.get())
def More():
number.set(number.get() + 1)
print("The number is now ", number.get())
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, textvariable = number).pack(pady = 20)
MakeLabel(number)
root.mainloop()
I am trying to make a simple calculator for a game I play as a random project. I found myself very confused on how to go about doing this; I want the user to enter a number in the textbox and it will multiply that number by 64000 and display it in a label above. But, I cannot find out anywhere how to do this. This is just a small practice thing and im amazed I cannot figure it out. Please help meh! Here is my code:
from Tkinter import *
####The GUI#####
root = Tk()
#Title#
root.wm_title("TMF Coin Calculator")
####The Widgets####
a = StringVar()
b = StringVar()
def multiply_a():
d = (int(a) * 64000)
e = str(d)
b.set(e)
b.trace("w", multiply_a)
#Top Label#
top_label = Label(root, fg="red", text="Type the ammount of Coin Stacks you have.")
top_label.grid(row=0, column=0)
#The Output Label#
output_label = Label(root, textvariable=b, width = 20)
output_label.grid(row = 1, column=0)
#User Entry Box#
user_input_box = Entry(root, textvariable=a, width=30)
user_input_box.grid(row=2, column=0)
root.mainloop()
You need to trace the variable that changes: a. Then you need to define multiply_a() to handle an arbitrary number of arguments with *args (happens to be 3 arguments in this case, but *args is fine here).
Go from:
def multiply_a():
d = (int(a) * 64000)
e = str(d)
b.set(e)
b.trace("w", multiply_a)
to:
def multiply_a(*args):
try:
myvar = int(a.get())
except ValueError:
myvar = 0
b.set(myvar * 64000)
a.trace("w", multiply_a)
This will additionally use 0 if the entered value can't be turned into an int.
import sys
from tkinter import *
def main():
mtext = ment.get()
mlabel2 = Label(top, text=mtext).pack()
def isbn():
digits = [(11 - i) * num for i, num in enumerate(map(int, list()))]
digit_11 = 11 - (sum(digits) % 11)
if digit_11 == 10:
digit_11 = 'X'
digits.append(digit_11)
isbn_number = "".join(map(str, digits))
label2 = Label(top, text = "Your ISBN number is",).pack()
top = Tk()
top.geometry("450x450+500+300")
top.title("Test")
button = Button(top,text="OK", command = isbn, fg = "red", bg="blue").pack()
label = Label(top, text = "Please enter the 10 digit number").pack()
ment= IntVar()
mEntry = Entry(top,textvariable=ment).pack()
Hello, I the code at the moment is a working stage, I just need a way of the results printing because at the moment it is not. I would also like the converter to work proper ally with 10 digits and the 11th digit being the number that the converter finds outs. Thanls
Note how the button's command calls the function to perform your operation:
from tkinter import *
def find_isbn(isbn, lbl):
if len(isbn) == 10:
mult = 11
total = 0
for i in range(len(isbn)):
total += int(isbn[i]) * mult
mult -= 1
digit_11 = 11 - (total % 11)
if digit_11 == 10:
digit_11 = 'X'
isbn += str(digit_11)
lbl.config(text=isbn)
top = Tk()
top.geometry("450x450+500+300")
top.title("Test")
button = Button(top, text="OK", command=lambda: find_isbn(mEntry.get(), mlabel2), fg="red", bg="blue")
button.pack()
label = Label(top, text="Please enter the 10 digit number")
label.pack()
mEntry = Entry(top)
mEntry.pack()
mlabel2 = Label(top, text='')
mlabel2.pack()
top.mainloop()
You also need to call .mainloop(), on your master widget to get the whole things started. It's also better to call .pack() on an object on a separate line. pack() and grid() return nothing so you won't be able to use other methods on the object once you do that.