I need help displaying "cannot convert negatives" in tkinter.
I want it to say "cannot convert negatives" when I type in a negative number.
Code:
from tkinter import *
def convert():
P = float(pound.get())
K = P * 0.453592
Kilogram.set(str(K))
input (P)
if (P) < 0:
print("cannot convert negitaves") # i need to display this when i run the program
else:
K = P * 0.453592
print(K)
my_window = Tk()
Kilogram = StringVar()
pound = StringVar()
label_1 = Label(my_window, text="Enter the pound")
label_2 = Label(my_window, text="Kilogram")
display_kilogram_label = Label(my_window, textvariable=Kilogram)
pound_entry = Entry(my_window, textvariable=pound)
convert_button = Button(my_window, text="Convert", command=convert)
label_1.grid(row=0, column=0)
pound_entry.grid(row=0, column=1)
label_2.grid(row=1, column=0)
display_kilogram_label.grid(row=1, column=1)
convert_button.grid(row=2, column=0)
my_window.mainloop()
I commented out the "input (P)" line, and refactored your convert function a little bit, now it works:
def convert():
P = float(pound.get())
# input (P)
if P < 0:
print("cannot convert negitaves") # i need to display this when i run the program
else:
K = P * 0.453592
Kilogram.set(str(K))
print(K)
Based on your feedback, I changed the convert function to display the error message as well:
def convert():
P = float(pound.get())
if P < 0:
Kilogram.set("Cannot convert negatives!")
else:
Kilogram.set(str(P * 0.453592))
Simply commenting the input(P) line is what you need to do to make your program run.
from tkinter import *
def convert():
P = float(pound.get())
K = P * 0.453592
Kilogram.set(str(K))
if (P) < 0:
print("cannot convert negitaves") # i need to display this when i run the program
else:
K = P * 0.453592
print(K)
my_window = Tk()
Kilogram = StringVar()
pound = StringVar()
label_1 = Label(my_window, text="Enter the pound")
label_2 = Label(my_window, text="Kilogram")
display_kilogram_label = Label(my_window, textvariable=Kilogram)
pound_entry = Entry(my_window, textvariable=pound)
convert_button = Button(my_window, text="Convert", command=convert)
label_1.grid(row=0, column=0)
pound_entry.grid(row=0, column=1)
label_2.grid(row=1, column=0)
display_kilogram_label.grid(row=1, column=1)
convert_button.grid(row=2, column=0)
my_window.mainloop()
Related
from tkinter import *
def c_to_f(celsius):
return str(float(celsius) * 1.8 + 32)
window = Tk()
f = Label(window, text="ºF")
f.pack()
finpt = Entry(window)
fvalue = finpt.get()
finpt.pack()
c = Label(window, text="ºC")
c.pack()
cinpt = Entry(window)
cvalue = cinpt.get()
cinpt.pack()
to_f = Button(window, text="Nach ºF umrechnen", command=finpt.insert(0, f"{c_to_f(cvalue)}"))
to_f.pack()
window.mainloop()
After pressing the button, I want to return the show the result of c_to_f(cvalue) in Label c. How can I manage that?
It is better to create another function for the button to_f and do the conversion and show result inside that function:
from tkinter import *
def c_to_f(celsius):
return str(float(celsius) * 1.8 + 32)
def convert_to_fahrenheit():
try:
f = c_to_f(cinpt.get())
finpt.delete(0, END)
finpt.insert(END, f)
except ValueError as ex:
print(ex)
window = Tk()
f = Label(window, text="ºF")
f.pack()
finpt = Entry(window)
#fvalue = finpt.get()
finpt.pack()
c = Label(window, text="ºC")
c.pack()
cinpt = Entry(window)
#cvalue = cinpt.get()
cinpt.pack()
to_f = Button(window, text="Nach ºF umrechnen", command=convert_to_fahrenheit)
to_f.pack()
window.mainloop()
Your code is giving too much problem.
Try this:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title('Temperature Converter')
root.geometry('300x70')
root.resizable(False, False)
def fahrenheit_to_celsius(f):
""" Convert fahrenheit to celsius
"""
return (f - 32) * 5/9
frame = ttk.Frame(root)
options = {'padx': 5, 'pady': 5}
temperature_label = ttk.Label(frame, text='Fahrenheit')
temperature_label.grid(column=0, row=0, sticky='W', **options)
temperature = tk.StringVar()
temperature_entry = ttk.Entry(frame, textvariable=temperature)
temperature_entry.grid(column=1, row=0, **options)
temperature_entry.focus()
def convert_button_clicked():
f = float(temperature.get())
c = fahrenheit_to_celsius(f)
result = f'{f} Fahrenheit = {c:.2f} Celsius'
result_label.config(text=result)
convert_button = ttk.Button(frame, text='Convert')
convert_button.grid(column=2, row=0, sticky='W', **options)
convert_button.configure(command=convert_button_clicked)
result_label = ttk.Label(frame)
result_label.grid(row=1, columnspan=3, **options)
frame.grid(padx=10, pady=10)
root.mainloop()
Screenshot:
I am creating a code that allows the user to enter 4 values (a, b, c, and d) for the equation (ax^3+bx^2+cx+d), then the program will output the graph on a window (I am using Tkinter). however, the code for some reason doesn't work.
To explain a bit my code in the input_check process I am outputting a button on a window with a blank box for the input. when the input is entered the program will check if it is the same as 3 (I will be adding more equations after (therefore it will check which equation the user wants), then it should asks for the values of a, b, c, and d, however after than it gives an error.
My code is:
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
root = Tk()
root.title("Maths Plot")
root.geometry("600x500")
root.configure(bg='dark blue')
# this function is just for fun at the moment
def foo():
print('working')
# navigation bar of the website
my_menu = Menu(root)
root.config(menu=my_menu)
# file menu
file_menu = Menu(my_menu)
my_menu.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='notebook', command=foo)
file_menu.add_command(label='open', command=foo)
file_menu.add_separator()
file_menu.add_command(label='copy', command=foo)
# edit menu
edit_menu = Menu(my_menu)
my_menu.add_cascade(label='Edit', menu=edit_menu)
edit_menu.add_command(label='add notebook', command=foo)
edit_menu.add_command(label='cell copy', command=foo)
edit_menu.add_separator()
edit_menu.add_command(label='paste cell', command=foo)
# checking which type of equation the user wants to enter on base of the number inputted
def input_check():
processing = FALSE
answer_int = int(answer1.get())
while processing == FALSE:
if answer_int == 1:
confirmation = Label(root, text="You have inputted the number 1")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=linear_equation())
execution.grid(row=4, column=1)
processing = TRUE
elif answer_int == 2:
confirmation = Label(root, text="You have inputted the number 2")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=quadratic_equation())
execution.grid(row=4, column=1)
processing = TRUE
elif answer_int == 3:
confirmation = Label(root, text="You have inputted the number 3")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=cubic_equation())
execution.grid(row=4, column=1)
processing = TRUE
elif answer_int == 4:
confirmation = Label(root, text="You have inputted the number 4")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=exponential_equation())
execution.grid(row=4, column=1)
processing = TRUE
else:
confirmation = Label(root, text="the answer you inputted is invalid, please try again.")
confirmation.grid(row=3, column=1)
label1 = Label(root, text="enter a number between 1 and 4 ")
answer1 = Entry(root)
button1 = Button(root, text='enter', command=input_check)
label1.grid(row=0, column=0)
answer1.grid(row=0, column=1)
button1.grid(row=1, column=1)
def linear_equation():
print("this is function 1")
def quadratic_equation():
print("this is function 2")
def cubic_equation():
a = ''
b = ''
c = ''
d = ''
# converting the Entries from string to float for future calcuations
def enter_click(event):
global a
global b
global c
global d
a = float(a_entry.get())
b = float(b_entry.get())
c = float(c_entry.get())
d = float(d_entry.get())
# code
x_axis = np.linspace(-10, 10, num=100)
y_base = [a * x_axis ** 3 + b * x_axis ** 2 + c * x_axis + d]
plt.figure(num=0, dpi=120)
plt.plot(x_axis, y_base, label="f(x)", linestyle='--')
plt.legend()
plt.grid(linestyle=':')
plt.xlim([-1000, 1000])
plt.ylim([-1000, 1000])
plt.title('graph')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
a_entry = Entry(root)
a_entry.grid(row=5, column=0)
b_entry = Entry(root)
b_entry.grid(row=6, column=0)
c_entry = Entry(root)
c_entry.grid(row=7, column=0)
d_entry = Entry(root)
d_entry.grid(row=8, column=0)
enter_button = Button(root, text="Enter")
enter_button.grid(row=9, column=0)
enter_button.bind("<Button-1>", enter_click)
enter_button.bind("<Return>", enter_click)
'''def cubic():
return a * x_axis ** 3 + b * x_axis ** 2 + c * x_axis + d'''
def exponential_equation():
print("this is function 4")
root.mainloop()
the error that I keep getting is:
ValueError: x and y must have same first dimension, but have shapes (10,) and (1, 10)
I tried to search online for any information but I didn't find anything usefull.
(I found some solutions that use canvas but I have no idea on how to use it).
Can anyone help me please?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to fill in a matrix, and at the same time if a for example "1/7" get entered that it converts to float ? but it doesn't work
import fractions
import tkinter as tk
from tkinter import *
import numpy as np
import pandas as pd
from fractions import Fraction
from tkinter.font import Font
from PIL import Image, ImageTk
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
import tkinter.messagebox
import os
import sys
#this function contain a small window that you need to put the number of criteria in ,which will be the dimension of the maTRIX , WHEN I FILL THE matrix and click submit for it to be saved it doesn't work
def be():
window = Tk()
window.title("Dimensions ")
window.geometry("300x200")
def variable():
global fn, f
fn = entry_1.get()
f = entry_2.get()
ln = StringVar()
df = []
name = StringVar()
def save():
for entries in range(len(df)):
df[entries] = name.get()
for entries in range(len(df)):
df = df.append({'Critere': df[entries].get()}, ignore_index=True)
print(df)
df
def open_window():
root = tk.Tk()
root.geometry("460x600")
root.title('AHP Application ')
# global f
# f=printent()
# print(f)
for i in range(int(f)):
# c = input("Enter valeur {}: ".format(i))
my_label = Label(root, text="Entrer le critere numero 0{} :".format(i + 1), width=24, font=("bold", 10))
my_label.grid(row=i, column=0, pady=20, padx=5)
my_entry = Entry(root)
my_entry.grid(row=i, column=1, pady=20, padx=5)
df.append(my_entry)
suivant1 = tk.Button(root, text="Suivant", width=8, borderwidth=3, command=hope).place(x=370, y=40)
fermer2 = tk.Button(root, text="Fermer", width=8, borderwidth=3).place(x=370, y=90)
root.mainloop()
label_1 = Label(window, text="Entrer L'Objectif de Votre projet :", width=24, font=("bold", 10))
label_1.place(x=3, y=0)
entry_1 = Entry(window)
entry_1.place(x=100, y=30)
label_2 = Label(window, text="Entrer le nombre de critère :", width=20, font=("bold", 10))
label_2.place(x=3, y=70)
entry_2 = Entry(window)
# Remove default 0
entry_2.delete(0, END)
entry_2.place(x=100, y=100)
suivant = tk.Button(window, text="suivant", borderwidth=3, command=lambda: [variable(), open_window()]).place(x=40,
y=150)
fermer = tk.Button(window, text="fermer", borderwidth=3).place(x=190, y=150)
def hope():
win = Tk()
win.title("Matrix")
win.geometry("700x500")
global f
print(f)
wrapper1 = LabelFrame(win, text="Enter matrix")
wrapper3 = LabelFrame(win, text="Resultats")
wrapper1.pack(fill="both", expand="yes", padx=50, pady=20)
wrapper3.pack(fill="both", expand="yes", padx=20, pady=10)
def convert_to_float(frac_str):
try:
return float(frac_str)
except ValueError:
num, denom = frac_str.split('/')
try:
leading, num = num.split(' ')
whole = float(leading)
except ValueError:
whole = 0
frac = float(num) / float(denom)
return whole - frac if whole < 0 else whole + frac
# empty arrays for your Entrys and StringVars
text_var = []
entries = []
matrix = []
# callback function to get your StringVars
def get_mat():
for i in range(rows):
matrix.append([])
for j in range(cols):
matrix[i].append(convert_to_float (text_var[i][j].get()))
print(matrix)
b = np.array(matrix, dtype=float, order='C')
print(b)
global df2, df, c
index = []
columns = []
for i in range(int(f)):
index.append("critère{}".format(i + 1))
columns.append("critère{}".format(i + 1))
df = pd.DataFrame(data=b, index=index, columns=columns)
print(df)
arr = df.to_numpy()
global c
c = []
for i in range(len(df)):
c.append(np.prod(arr[i].astype(float)))
df2 = pd.DataFrame(data=c, index=range(int(f)), columns=["hi"])
print(df2)
# Label(win, text="Enter matrix :", font=('arial', 10, 'bold'),
# bg="bisque2").place(x=20, y=20)
x2 = 0
y2 = 0
rows = int(f)
cols = int(f)
global df2, df, c
x = np.array(['1.1', '2.2', '3.3'])
for i in range(rows):
# append an empty list to your two arrays
# so you can append to those later
text_var.append([])
entries.append([])
for j in range(cols):
# append your StringVar and Entry
text_var[i].append(StringVar())
entries[i].append(Entry(win, textvariable=text_var[i][j], width=5))
entries[i][j].place(x=80 + x2, y=30 + y2)
x2 += 40
y2 += 30
x2 = 0
button = Button(wrapper1, text="Submit", bg='bisque3', width=15, command=get_mat)
button.place(x=300, y=80)
my_label = Label(wrapper3, text="Lamda Max:", width=24, font=("bold", 10))
my_label.grid(row=0, column=0, pady=20, padx=5)
my_entry = Entry(wrapper3)
my_entry.grid(row=0, column=1, pady=20, padx=5)
# my_entry.insert(0,lamba)
my_label1 = Label(wrapper3, text="Indice de Coherence (CI):", width=24, font=("bold", 10))
my_label1.grid(row=1, column=0, pady=20, padx=5)
my_entry1 = Entry(wrapper3)
my_entry1.grid(row=1, column=1, pady=20, padx=5)
my_label2 = Label(wrapper3, text="Indice de Racio (IC):", width=24, font=("bold", 10))
my_label2.grid(row=2, column=0, pady=20, padx=5)
my_entry2 = Entry(wrapper3)
my_entry2.grid(row=2, column=1, pady=20, padx=5)
def calcule():
global f
df3 = pd.DataFrame(data=c, index=range(int(f)))
df3 = pow(df2, 1 / int(f))
print("df3 is ")
print(df3)
# Somme
Somme = df3.sum()
print("la somme est ")
print(Somme)
# weights
B = df3 / Somme
print(" La matrice des Poids:")
print(B)
# verify if somme of B is 1 , if it is then we are on the right road
Somm = B.sum()
print(Somm)
# consistency check
print("A3")
C = np.dot(df, B)
print(C)
# consistency check
print("A4")
D = C / B
print(D)
# global lamba
# Consistency Index
# lambda
lamba = np.mean(D)
print("the average is ")
print(lamba.to_string())
my_entry.insert(0, lamba.to_string(index=False))
# n = float(n)
CI = (lamba - float(f)) / (float(f) - 1)
print("The consistency Index is")
print(CI.to_string())
my_entry1.insert(0, CI.to_string(index=False))
# consistency ratio
if int(f) == 3:
RI = 0.52
elif int(f) == 4:
RI = 0.89
elif int(f) == 5:
RI = 1.11
elif int(f) == 6:
RI = 1.25
elif int(f) == 7:
RI = 1.35
elif int(f) == 8:
RI = 1.4
elif int(f) == 9:
RI = 1.45
elif int(f) == 10:
RI = 1.49
print("THE RATIO IS :")
print(RI)
CR = float(CI / RI)
my_entry2.insert(0, CR)
if CR < 0.1:
print("Congratulations ,Your criterias are consistent to go ahead \nThe value of consistency ratio is ",
CR,
"which is less han 0.1 ")
else:
print("you need to re-fill the matrix", CR)
button = Button(wrapper3, text="calcule", bg='bisque3', width=15, command=calcule)
button.place(x=500, y=100)
a = IntVar()
win.mainloop()
window.mainloop()
be()
Python actually has a built-in module just for this, which also has support for arbitrary-precision arithmetic and conversion to native floats.
>>> from fractions import Fraction
>>> frac = Fraction("1/7")
>>> float(fract)
0.14285714285714285
Easy to use, and works out-of-the-box. You can also convert it to an integer ratio, in case you want more accuracy than a native float can provide:
>>> frac.as_integer_ratio()
(1, 7)
The reason why float("1/7") doesn't work is because it's not a valid representation of an actual float: it's an integer ratio. Fractions, however, which provides native conversion to-and-from floats, does.
I work on a program that calculates the macros of each meal. You can enter a value in gram and it calculates for each aliment your intake. I would like now to add these values together when I push multiple buttons. Then I'll display the value somewhere and maybe I could do a graph after.
Here I show what my program looks like :
import tkinter as tk
def value_kiwi():
value = ent_quantity.get()
formula = (float(value)/100)
cal = 53
pro = 1.6
glu = 11.1
li = 0.3
Calories = (cal) * formula
Protéines = (pro) * formula
Glucides = (glu) * formula
Lipides = (li) * formula
lbl_cal["text"] =f"{Calories}"
lbl_prot["text"] = f"{Protéines}"
lbl_glu["text"] = f"{Glucides}"
lbl_lip["text"] = f"{Lipides}"
def value_banane():
value = ent_quantity.get()
formula = (float(value)/100)
cal = 90
pro = 1.5
glu = 20.1
li = 0
Calories = (cal) * formula
Protéines = (pro) * formula
Glucides = (glu) * formula
Lipides = (li) * formula
lbl_cal["text"] =f"{Calories}"
lbl_prot["text"] = f"{Protéines}"
lbl_glu["text"] = f"{Glucides}"
lbl_lip["text"] = f"{Lipides}"
window = tk.Tk()
window.title("Calculateur de Calories et Nutriments")
frm_entry = tk.Frame(master=window)
ent_quantity = tk.Entry(master=frm_entry, width=5)
ent_quantity.grid(row=1, column=0,)
lbl_cal = tk.Label(master=window)
lbl_cal.grid(row=1, column=1,)
lbl_prot = tk.Label(master=window)
lbl_prot.grid(row=1, column=2)
lbl_glu = tk.Label(master=window)
lbl_glu.grid(row=1, column=3)
lbl_lip = tk.Label(master=window)
lbl_lip.grid(row=1, column=4)
btn_kiwi = tk.Button(
master=window,
text="Kiwi",
command=value_kiwi,
)
btn_banane = tk.Button(
master=window,
text="Banane",
command=value_banane,
)
lbl_calories = tk.Label(master=window, text="Calories",)
lbl_proteines = tk.Label(master=window, text="Protéines")
lbl_glucides = tk.Label(master=window, text="Glucides")
lbl_lipides = tk.Label(master=window, text="Lipides")
lbl_fruits = tk.Label(master=window, text="Fruits")
frm_entry.grid(row=1, column=0, padx=10)
lbl_calories.grid(row=0,column=1, padx=5, sticky="w")
lbl_proteines.grid(row=0, column=2, padx=10)
lbl_glucides.grid(row=0, column=3, padx=10)
lbl_lipides.grid(row=0,column =4, padx=10)
lbl_fruits.grid(row=1,column =5, padx=10)
btn_kiwi.grid(row=2, column=5, pady=10)
btn_banane.grid(row=3, column=5, pady=10)
window.mainloop()
Ok, I think I improved Your code:
from tkinter import Tk, Button, Entry, Label
class MainWindow(Tk):
def __init__(self):
Tk.__init__(self)
self.title('Nutrient calculator')
# entry
Label(self, text='Amount').grid(row=0, column=0)
self.amount = Entry(self, width=5, bg='light grey')
self.amount.grid(row=1, column=0)
# calories
Label(self, text='Calories').grid(row=0, column=1)
self.calories = Label(self)
self.calories.grid(row=1, column=1)
# proteins
Label(self, text='Proteins').grid(row=0, column=2)
self.proteins = Label(self)
self.proteins.grid(row=1, column=2)
# glucose
Label(self, text='Glucose').grid(row=0, column=3)
self.glucose = Label(self)
self.glucose.grid(row=1, column=3)
# lipids
Label(self, text='Lipids').grid(row=0, column=4)
self.lipids = Label(self)
self.lipids.grid(row=1, column=4)
# list of all labels
self.data_labels = [self.calories, self.proteins, self.glucose, self.lipids]
# error label for if no value is entered or it cannot be converted
self.error_label = Label(self, text='Use integer or float value!')
# stuff for adding multiple foods
self.do_add = False
self.nutrient_list = []
self.plus_btn = Button(self, text='Add', command=self.add)
self.plus_btn.grid(row=3, column=0, columnspan=4, sticky='nwes')
def display_values(self, value_list):
self.nutrient_list.append(value_list)
if len(self.nutrient_list) == 2 and not self.do_add:
self.nutrient_list.pop(0)
elif len(self.nutrient_list) > 2 and not self.do_add:
self.nutrient_list = [self.nutrient_list[-1]]
print(self.nutrient_list)
if self.do_add:
value_list = []
for i in range(len(self.nutrient_list[0])):
total_value = 0
for item in self.nutrient_list:
total_value += item[i]
value_list.append(total_value)
for text, label in zip(value_list, self.data_labels):
label.config(text=f'{text:.2f}')
self.do_add = False
def handle_value_error(self):
self.error_label.grid(row=2, column=0, columnspan=4)
def add(self):
self.do_add = True
self.amount.delete(0, 'end')
class Values:
def __init__(self, name, row, column, calories, proteins, glucose, lipids):
self.parent = root
self.name = name
self.row = row
self.column = column
self.calories = calories
self.proteins = proteins
self.glucose = glucose
self.lipids = lipids
self.stuff_list = [self.calories, self.proteins, self.glucose, self.lipids]
self.button = Button(self.parent, text=self.name, command=self.set_values)
self.button.grid(row=self.row, column=self.column, sticky='nwse')
def set_values(self):
value_list = []
value_ = self.parent.amount.get()
try:
formula = float(value_) / 100
self.parent.error_label.grid_forget()
for item in self.stuff_list:
item *= formula
value_list.append(item)
self.parent.display_values(value_list)
except ValueError:
self.parent.handle_value_error()
root = MainWindow()
kiwi = Values('Kiwi', 2, 4, calories=53, proteins=1.6, glucose=11.1, lipids=0.3)
banana = Values('Banana', 3, 4, calories=90, proteins=1.5, glucose=20.1, lipids=0)
root.mainloop()
it is not necessarily better however a few benefits from using this code are:
better organization (IMO) since it uses classes which make it pretty neat (however You have to have an understanding over them)
takes less space - what I mean is that now, to define a new food, You just have to initiate the Values class and give it the necessary arguments. You can take an example from the given instances.
possibly easier to expand (both because better organization and takes less space)
I edited the code so now it should have that functionality, the way it works is You choose an amount , then fruit and if You want to add more, press add button, then choose amount, press food and it will display the total so far, then again, if You want to add more press add and then put in an amount and press the fruit, currently the way to 'clear' is to press any food button and it should then reset the whole list and keep only the one that was just pressed and then repeat.
I'm trying to write calculator code which contains only plus mode and minus mode and BMI calculator. I've tried everything I know so far but I can't figure it out that why my code is unable to use
Here is my Bmi code:
from tkinter import *
def bmi():
kg = int(box1.get())
m = int(box2.get())
result =(kg)/(m^2)
result.configure(result).grid(row=2,column=1)
return
root = Tk()
root.option_add("*font", "impact 16")
Label(root, text= "wight(kg.)").grid(row=0,column=0)
box1 = Entry(root).grid(row=0,column=1)
Label(root, text= "hight(m.)").grid(row=1,column=0)
box2 = Entry(root).grid(row=1,column=1)
Label(root, text= "BMI",command=bmi).grid(row=2,column=0)
Button(root, text= "calculate").grid(row=3,columnspan=2)
root.mainloop()
and there is my calculator code
import tkinter as tk
def show_output():
number = int(number1_input.get())
if number == 1:
output_label.configure(text="plus")
number0_ask = tk.Label(master=window, text='input first number')
number0_input = tk.Entry(master=window,width= 15)
number2_ask = tk.Label(master=window, text='input second number')
number2_input = tk.Entry(master=window, width=15)
sum = int(number0_input)+int(number2_input)
output_label2.configure(sum)
elif number == 2:
output_label.configure(text="plus")
number0_ask = tk.Label(master=window, text='input first number')
number0_input = tk.Entry(master=window, width=15)
number2_ask = tk.Label(master=window, text='input second number')
number2_input = tk.Entry(master=window, width=15)
sum = int(number0_input) + int(number2_input)
output_label2.configure(sum)
else:
output_label2.configure("none of our program")
return
window = tk.Tk()
window.title("calulator")
window.minsize(width=400, height=400)
tittle_label = tk.Label(master=window, text="enter order 1 for plus 2 for minus")
tittle_label.pack(pady=20)
number1_input = tk.Entry(master=window, width=15)
number1_input.pack(pady=20)
go_button = tk.Button(master=window, text="result", command=show_output, width=15,
height=2)
go_button.pack(pady=20)
output_label = tk.Label(master=window)
output_label.pack(pady=20)
output_label2 = tk.Label(master=window)
output_label2.pack(pady=20)
window.mainloop()