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()
Related
import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame,text = "Print", command = lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame,height = 5, width = 20)
freek.pack()
input_a = freek.get(1.0, "end-1c")
print(input_a)
fruit = 0
fad = input_a[fruit:fruit+1]
print(fad)
schepje = len(input_a.strip("\n"))
print(schepje)
def zandkasteel():
lbl.config(text = "Ingevulde string: "+input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint()
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text = "")
lbl.pack()
frame.mainloop()
I need to get the string that was entered into the text entry field freek. I have tried to assign that string to input_a, but the string doesn't show up.
Right now, input_a doesn't get anything assigned to it and seems to stay blank. I had the same function working before implementing a GUI, so the problem shouldn't lie with the def zandkasteel.
To be honest I really don't know what to try at this point, if you happen to have any insights, please do share and help out this newbie programmer in need.
Here are some simple modifications to your code that shows how to get the string in the Text widget when it's needed — specifically when the zandkasteel() function gets called in response to the user clicking on the Print button.
import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame, text="Print", command=lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame, height=5, width=20)
freek.pack()
def zandkasteel():
input_a = freek.get(1.0, "end-1c")
print(f'{input_a=}')
fruit = 0
fad = input_a[fruit:fruit+1]
print(f'{fad=}')
schepje = len(input_a.strip("\n"))
print(f'{schepje=}')
lbl.config(text="Ingevulde string: " + input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint(1, 3)
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text="")
lbl.pack()
frame.mainloop()
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")
import tkinter as tk
Hoogte = 900
breedte = 1440
def doelwitpress(argumenten):
if argumenten == 1:
input("1")
if argumenten == 2:
input("2")
if argumenten == 3:
input("3")
import random
print('Kies uit 1 (kleinst), 2 (kleiner) of 3 (grootsts):')
willekeurigwoord = input()
kleinstedoelwit = ['beneficial', 'eloquent', 'in proximity']
x = random.choice(kleinstedoelwit)
if (willekeurigwoord == 1):
print(x)
kleineredoelwit = ['useful', 'advise', 'commence']
y = random.choice(kleineredoelwit)
if (willekeurigwoord == "2"):
print(y)
grootstedoelwit = ['vehicle', 'combined', 'uproar']
z = random.choice(grootstedoelwit)
if (willekeurigwoord == "3"):
print(z)
root = tk.Tk()
GrafischeUIcanvas = tk.Canvas(root, height=Hoogte)
GrafischeUIcanvas = tk.Canvas(root, width=breedte)
GrafischeUIcanvas.pack()
achtergrondkleur = tk.Frame(root, bg='#6BAB55')
achtergrondkleur.place(relwidt=1, relheight=1)
kleinstedoelwit = tk.Button(root, text="kleinste doelwit", command=lambda: doelwitpress(1))
kleineredoelwit = tk.Button(root, text="kleinere doelwit", command=lambda: doelwitpress(2))
grootstedoelwit = tk.Button(root, text="grootste doelwit", command=lambda: doelwitpress(3))
kleinstedoelwit.pack(side="left")
kleineredoelwit.pack(side="bottom")
grootstedoelwit.pack(side="right")
root.mainloop()
when i only run my code without gui i can get a word out but i have to manually type it in. I want my tkinter button to be my input and get an output from my code. I basically want to press a button in the UI, the UI then inputs a number and that number equals to one of the lists whith random words. The only thing that happens right now is that it shows the input of my press and then it crashes after 1 input. It doesnt even display 1 random chosen word.
Im using tkinter and random.choice
You should be using Entry widget to get the input from the user and Label or a messagebox to display output.
I have rewritten your code, without changing any logic. (Note: This is only for demonstration purposes as I have no idea how your GUI should come together. It's up to you to make further changes)
In the below code, I have set entry and entry2 to a variable var and var1 respectively. You can use this variable to get and set the value in the Entry widget as shown in the below code.
For output, I have used a label. You may change the text by using label.config(text='abc') or label.configure(text='abc') or just by accessing the text like lable[text] = 'abc'
import tkinter as tk
import random
Hoogte = 900
breedte = 1440
def doelwitpress(argumenten):
if argumenten == 1:
var.set('1')
if argumenten == 2:
var.set('2')
if argumenten == 3:
var.set('3')
lbl['text'] = 'Kies uit 1 (kleinst), 2 (kleiner) of 3 (grootsts):'
#print('Kies uit 1 (kleinst), 2 (kleiner) of 3 (grootsts):')
#willekeurigwoord = input()
kleinstedoelwit = ['beneficial', 'eloquent', 'in proximity']
x = random.choice(kleinstedoelwit)
if (var2.get() == '1'):
lbl['text'] = x
#print(x)
kleineredoelwit = ['useful', 'advise', 'commence']
y = random.choice(kleineredoelwit)
if (var2.get() == "2"):
lbl['text'] = y
#print(y)
grootstedoelwit = ['vehicle', 'combined', 'uproar']
z = random.choice(grootstedoelwit)
if (var2.get() == "3"):
lbl['text'] = z
#print(z)
root = tk.Tk()
var = tk.StringVar()
var2 = tk.StringVar()
GrafischeUIcanvas = tk.Canvas(root, height=Hoogte)
GrafischeUIcanvas = tk.Canvas(root, width=breedte)
GrafischeUIcanvas.pack()
achtergrondkleur = tk.Frame(root, bg='#6BAB55')
achtergrondkleur.place(relwidt=1, relheight=1)
#achtergrondkleur.pack()
kleinstedoelwit = tk.Button(root, text="kleinste doelwit", command=lambda: doelwitpress(1))
kleineredoelwit = tk.Button(root, text="kleinere doelwit", command=lambda: doelwitpress(2))
grootstedoelwit = tk.Button(root, text="grootste doelwit", command=lambda: doelwitpress(3))
kleinstedoelwit.pack(side="left")
kleineredoelwit.pack(side="bottom")
grootstedoelwit.pack(side="right")
lbl = tk.Label(root, bg='#6BAB55', fg='red')
lbl.pack()
entry = tk.Entry(root, textvariable=var)
entry.pack()
entry2 = tk.Entry(root, textvariable=var2)
entry2.pack()
root.mainloop()
I'm trying to show a sequence of numbers on the screen at regular intervals.
I'm new to python so it may be something obvious but I have tried .after and pygame.time.wait, but neither worked.
this is the code:
from tkinter import*
from random import *
import time
my_list = []
def Create_NUM(event):
x = 0
for x in range(level + 2):
button1.destroy()
num = randint(1, 100)
my_list.append(num)
Label(root, text=num,fg="red").pack()
one.pack()
time.sleep(2)
root=Tk()
num = 0
level = 1
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(bottomFrame, text="Click to start game",fg="red")
button1.bind("<Button-1>", Create_NUM)
button1.pack()
root.mainloop()
I assume you want to show new number in place of old number, not below it.
import tkinter as tk
import random
def start():
# hide button
button.pack_forget()
# run `add_number` first time
add_number(level+2)
def add_number(x):
num = random.randint(1, 100)
my_list.append(num)
label['text'] = num
if x > 0:
# repeat after 2000ms (2s)
root.after(2000, add_number, x-1)
else:
# show button again after the end
button.pack()
# --- main ---
my_list = []
level = 1
root = tk.Tk()
label = tk.Label(root)
label.pack()
button = tk.Button(root, text="Click to start game", command=start)
button.pack()
root.mainloop()
Just use this simple command in your function root.update()
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))