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.
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 trying to make a GUI version of a drinking game, which involves throwing dice. I 'throw the dice' virtually, but want to display the outcome on the screen. I thought using Label() would be most useful, but i'm having trouble updating that text (the throw_text variable) when a new dice throw is done.
Instead of the text updating on the screen, a new text appears below the previous one with the new throw.
I don't want a cascading stream of text, but just one singular text that updates at the dice being thrown i.e. when the 'Roll!' button is pressed.
I've seen people do it using the Stringvar(), however i must be doing it wrong as it does not have an effect on the appearance.
from tkinter import *
dim = [900, 600]
root = Tk()
root.geometry(f"{dim[0]}x{dim[1]}")
root.title("Mex")
root.iconbitmap("dice.ico")
lbl = Label(root, font=("Times", 200))
num = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685']
d1 = None
d2 = None
throw_txt = StringVar()
def roll_dice():
global d1, d2
d1 = random.choice(num)
d2 = random.choice(num)
lbl.config(text=f"{d1}{d2}")
lbl.pack()
lbl.place(x=dim[0] / 3.8, y=50)
print("Throw:", check_throw(convert_symbol()))
throw_txt = str(check_throw(convert_symbol()))
txt = Label(root, text=throw_txt)
txt.pack(side=TOP)
def convert_symbol():
d1_num = None
d2_num = None
for n in num:
if n == d1:
d1_num = num.index(n) + 1
if n == d2:
d2_num = num.index(n) + 1
if d2_num > d1_num:
throw = f"{d2_num}{d1_num}"
else:
throw = f"{d1_num}{d2_num}"
return throw
def check_throw(t):
num_t = int(t)
if num_t == 21:
return "Mex"
elif num_t % 11 == 0:
return f"Koning: {int(num_t / 11 * 100)}"
elif num_t % 31 == 0:
return "Slok uitdelen"
else:
return str(num_t)
roll_btn = Button(root, text="Roll!", width=10, command=roll_dice)
roll_btn.config(font=("Bahnschrift", 20))
roll_btn.pack()
roll_btn.place(x=dim[0] / 2.5, y=25)
roll_btn = Button(root, text="Convert", width=10, command=convert_symbol)
roll_btn.config(font=("Bahnschrift", 20))
roll_btn.pack()
roll_btn.place(x=dim[0] / 2.5, y=500)
root.mainloop()
You could use the configure attribute instead of storing the text of the Label widget into a separate variable.
Take a quick look at this code:
from tkinter import *
root = Tk()
root.title("my game")
def change_text():
mylabel.configure(text="You just hit the button!")
mylabel = Label(root, text="Hit the button pls")
mylabel.grid(column=0, row=1, sticky='w')
mybutton = Button(root, text="Click me", command=change_text)
mybutton.grid(column=0, row=2, sticky='w')
root.mainloop()
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 have made a calculator in tkinter python. When I want to type in 21, it types 12 because of the way the digits are entered into the entry box. I want to correct that.
I have tried tag-right but it doesn't work for entry label.
"""
Created on Thu Sep 19 17:49:21 2019
#author: Ishita
"""
x = 0
def add_one():
if(x == 0):
entry1.insert(0, "1")
elif(x == 1):
entry2.insert(0, "1")
.
.
.
.
def next_num():
global x
x = 1
def add_num():
result["text"] = ""
num1 = entry1.get()
num2 = entry2.get()
output = int(num1) + int(num2)
result["text"] = str(output)
.
.
.
.
def clear_nums():
entry1.delete(0, "end")
entry2.delete(0, "end")
result["text"] = ""
global x
x = 0
import tkinter as tk
from tkinter import *
calc = tk.Tk()
calc.title("Basic Calculator")
calc.geometry("300x600")
calc.config(background="white")
mainframe1 = tk.Frame(calc)
mainframe1.pack()
entry1 = tk.Entry(mainframe1, width=3, background="white", font="Times 20")
entry1.insert("end", " ")
entry1.configure(justify="right")
entry2 = tk.Entry(mainframe1, width=3, background="white", font="TImes 20")
entry2.insert("end", " ")
entry2.configure(justify="right")
result = tk.Label(mainframe1, width=3, font="Times 20")
button1 = tk.Button(mainframe1, height=2, width=4, background="white", text="1", font="Times 20", command=add_one)
calc.mainloop()
On typing 1 and 2, the entry box should give 12 but it gives 21. The numerical entries are happening with the numbers on the application(not with keyboard).
If you want to insert values at the end of the entry, you need to specify "end" (or the constant END from tkinter) instead of zero:
def add_one():
if(x == 0):
entry1.insert("end", "1")
elif(x == 1):
entry2.insert("end", "1")
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()