8.5 C
New York
Wednesday, November 19, 2025
Blog Page 17

How to Code Calculator with Python, Tkinter, using ChatGPT

🧮 Ready to dive into the world of advanced calculators? In this comprehensive tutorial, we’ll guide you through the process of creating an intelligent scientific calculator using the power of Python, Tkinter for the user interface, and ChatGPT for natural language interaction. 🔍 We’ll cover a wide range of topics, including: Designing an intuitive user interface with Tkinter. Implementing advanced arithmetic and scientific functions. Enhancing user experience with natural language input using ChatGPT. Building a feature-rich calculator that simplifies complex calculations. 💡 Whether you’re a student, engineer, or math enthusiast, this tutorial will empower you to create your own powerful scientific calculator tailored to your needs. #Python #Tkinter #ChatGPT #ScientificCalculator #Tutorial #technotribe #technology #imranhussainkhan

 

Source Code Here

 

import tkinter as tk
import math
def button_click(number):
    current = entry.get()
    entry.delete(0, tk.END)
    entry.insert(tk.END, current + str(number))
def button_clear():
    entry.delete(0, tk.END)
def button_equal():
    expression = entry.get()
    try:
        result = eval(expression)
        entry.delete(0, tk.END)
        entry.insert(tk.END, result)
    except Exception as e:
        entry.delete(0, tk.END)
        entry.insert(tk.END, “Error”)
def button_sin():
    value = float(entry.get())
    result = math.sin(math.radians(value))
    entry.delete(0, tk.END)
    entry.insert(tk.END, result)
def button_cos():
    value = float(entry.get())
    result = math.cos(math.radians(value))
    entry.delete(0, tk.END)
    entry.insert(tk.END, result)
def button_tan():
    value = float(entry.get())
    result = math.tan(math.radians(value))
    entry.delete(0, tk.END)
    entry.insert(tk.END, result)
def button_log():
    value = float(entry.get())
    result = math.log10(value)
    entry.delete(0, tk.END)
    entry.insert(tk.END, result)
def button_factorial():
    value = int(entry.get())
    result = math.factorial(value)
    entry.delete(0, tk.END)
    entry.insert(tk.END, result)
root = tk.Tk()
root.title(“Calculator”)
entry = tk.Entry(root, width=30, font=(“Arial”, 18))
entry.grid(row=0, column=0, columnspan=5, padx=10, pady=10)
buttons = [
    ‘7’, ‘8’, ‘9’, ‘/’,
    ‘4’, ‘5’, ‘6’, ‘*’,
    ‘1’, ‘2’, ‘3’, ‘-‘,
    ‘0’, ‘.’, ‘=’, ‘+’,
    ‘C’, ‘sin’, ‘cos’, ‘tan’,
    ‘log’, ‘!’, ‘(‘, ‘)’
]
row = 1
col = 0
for button in buttons:
    if button == ‘=’:
        tk.Button(root, text=button, width=6, height=2, command=button_equal).grid(row=row, column=col)
    elif button == ‘C’:
        tk.Button(root, text=button, width=6, height=2, command=button_clear).grid(row=row, column=col)
    elif button == ‘sin’:
        tk.Button(root, text=button, width=6, height=2, command=button_sin).grid(row=row, column=col)
    elif button == ‘cos’:
        tk.Button(root, text=button, width=6, height=2, command=button_cos).grid(row=row, column=col)
    elif button == ‘tan’:
        tk.Button(root, text=button, width=6, height=2, command=button_tan).grid(row=row, column=col)
    elif button == ‘log’:
        tk.Button(root, text=button, width=6, height=2, command=button_log).grid(row=row, column=col)
    elif button == ‘!’:
        tk.Button(root, text=button, width=6, height=2, command=button_factorial).grid(row=row, column=col)
    else:
        tk.Button(root, text=button, width=6, height=2, command=lambda key=button: button_click(key)).grid(row=row, column=col)
    col += 1
    if col > 4:
        col = 0
        row += 1
root.mainloop()

 

Code NotePad in Python using ChatGPT

 

📝 In this tutorial, we’ll embark on a journey to develop a unique and intelligent notepad using Python and the incredible capabilities of ChatGPT. Say goodbye to ordinary text editors and welcome your own AI-powered writing assistant. 🌟 What to Expect: Build a feature-rich text editor with Python. Harness the power of ChatGPT to assist you in writing and generating content. Customize and enhance your notepad to make writing more efficient and enjoyable. Don’t forget to like, share, and subscribe for more exciting coding tutorials! #Python #ChatGPT #TextEditor #AIWritingAssistant #CodingTutorial #technotribe #technology #imranhussainkhan

 

 Source Code Here

import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import font as tkfont
def open_file():
    file_path = filedialog.askopenfilename()
    if file_path:
        with open(file_path, ‘r’) as file:
            text.delete(‘1.0’, tk.END)
            text.insert(tk.END, file.read())
def save_file():
    file_path = filedialog.asksaveasfilename(defaultextension=”.txt”)
    if file_path:
        with open(file_path, ‘w’) as file:
            file.write(text.get(‘1.0’, tk.END))
def save_file_as():
    file_path = filedialog.asksaveasfilename(defaultextension=”.txt”)
    if file_path:
        with open(file_path, ‘w’) as file:
            file.write(text.get(‘1.0’, tk.END))
def copy_text():
    text.clipboard_clear()
    text.clipboard_append(text.selection_get())
def cut_text():
    copy_text()
    text.delete(‘sel.first’, ‘sel.last’)
def paste_text():
    text.insert(‘insert’, text.clipboard_get())
def undo():
    try:
        text.edit_undo()
    except Exception:
        pass
def redo():
    try:
        text.edit_redo()
    except Exception:
        pass
def change_font():
    selected_font = font_var.get()
    text.config(font=(selected_font, font_size_var.get()))
def change_color():
    selected_color = color_var.get()
    text.config(fg=selected_color)
def print_text():
    try:
        text.printout()
    except Exception as e:
        messagebox.showerror(“Error”, f”Printing failed: {str(e)}”)
# Create the main window
root = tk.Tk()
root.title(“Notepad”)
# Create a Text widget for editing
text = tk.Text(root)
text.pack()
# Create a menu bar
menu_bar = tk.Menu(root)
root.config(menu=menu_bar)
# Create a File menu
file_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label=”File”, menu=file_menu)
file_menu.add_command(label=”Open”, command=open_file)
file_menu.add_command(label=”Save”, command=save_file)
file_menu.add_command(label=”Save As”, command=save_file_as)
file_menu.add_separator()
file_menu.add_command(label=”Print”, command=print_text)
file_menu.add_separator()
file_menu.add_command(label=”Exit”, command=root.quit)
# Create an Edit menu
edit_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label=”Edit”, menu=edit_menu)
edit_menu.add_command(label=”Undo”, command=undo)
edit_menu.add_command(label=”Redo”, command=redo)
edit_menu.add_separator()
edit_menu.add_command(label=”Copy”, command=copy_text)
edit_menu.add_command(label=”Cut”, command=cut_text)
edit_menu.add_command(label=”Paste”, command=paste_text)
# Create a View menu
view_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label=”View”, menu=view_menu)
font_var = tkfont.Font(family=”Arial”, size=12)
font_size_var = tk.StringVar()
font_size_var.set(font_var.actual()[“size”])
font_menu = tk.Menu(view_menu, tearoff=0)
view_menu.add_cascade(label=”Font”, menu=font_menu)
font_menu.add_radiobutton(label=”Arial”, variable=font_var, value=”Arial”, command=change_font)
font_menu.add_radiobutton(label=”Times New Roman”, variable=font_var, value=”Times New Roman”, command=change_font)
font_menu.add_radiobutton(label=”Courier New”, variable=font_var, value=”Courier New”, command=change_font)
font_menu.add_radiobutton(label=”Verdana”, variable=font_var, value=”Verdana”, command=change_font)
font_size_menu = tk.Menu(view_menu, tearoff=0)
view_menu.add_cascade(label=”Font Size”, menu=font_size_menu)
font_size_menu.add_radiobutton(label=”10″, variable=font_size_var, value=”10″, command=change_font)
font_size_menu.add_radiobutton(label=”12″, variable=font_size_var, value=”12″, command=change_font)
font_size_menu.add_radiobutton(label=”14″, variable=font_size_var, value=”14″, command=change_font)
font_size_menu.add_radiobutton(label=”16″, variable=font_size_var, value=”16″, command=change_font)
color_var = tk.StringVar()
color_var.set(“black”)
color_menu = tk.Menu(view_menu, tearoff=0)
view_menu.add_cascade(label=”Text Color”, menu=color_menu)
color_menu.add_radiobutton(label=”Black”, variable=color_var, value=”black”, command=change_color)
color_menu.add_radiobutton(label=”Red”, variable=color_var, value=”red”, command=change_color)
color_menu.add_radiobutton(label=”Blue”, variable=color_var, value=”blue”, command=change_color)
# Start the main event loop
root.mainloop()

Build Tic Tac Toe Game using Python Code with the Help of ChatGPT

In this tutorial, I’ll try to provide you with how to get help from ChatGPT and code the Game. Try this source Code.

import tkinter as tk
from tkinter import messagebox
def check_winner():
    for combo in winning_combinations:
        a, b, c = combo
        if board[a] == board[b] == board[c] != “”:
            return board[a]
    return None
def check_draw():
    return “” not in board
def handle_click(index):
    global current_player
    global winner
    if board[index] == “” and not winner:
        board[index] = current_player
        buttons[index].config(text=current_player, state=tk.DISABLED)
        current_player = “X” if current_player == “O” else “O”
        winner = check_winner()
        if winner:
            messagebox.showinfo(“Tic Tac Toe”, f”Player {winner} wins!”)
            reset_game()
        elif check_draw():
            messagebox.showinfo(“Tic Tac Toe”, “It’s a draw!”)
            reset_game()
def reset_game():
    global board, current_player, winner
    board = [“”] * 9
    current_player = “X”
    winner = None
    for button in buttons:
        button.config(text=””, state=tk.NORMAL)
def exit_game():
    root.destroy()
winning_combinations = [(0, 1, 2), (3, 4, 5), (6, 7, 8),
                        (0, 3, 6), (1, 4, 7), (2, 5, 8),
                        (0, 4, 8), (2, 4, 6)]
root = tk.Tk()
root.title(“Tic Tac Toe”)
# Dark mode colors
bg_color = “#333”
text_color = “white”
font_size = 16
root.configure(bg=bg_color)
board = [“”] * 9
current_player = “X”
winner = None
buttons = [tk.Button(root, text=””, width=10, height=3, command=lambda i=i: handle_click(i), bg=bg_color, fg=text_color, font=(“Arial”, font_size)) for i in range(9)]
for i, button in enumerate(buttons):
    row = i // 3
    col = i % 3
    button.grid(row=row, column=col)
reset_button = tk.Button(root, text=”Reset”, command=reset_game, bg=bg_color, fg=text_color, font=(“Arial”, font_size))
reset_button.grid(row=3, column=0, columnspan=2)
exit_button = tk.Button(root, text=”Exit”, command=exit_game, bg=bg_color, fg=text_color, font=(“Arial”, font_size))
exit_button.grid(row=3, column=2, columnspan=2)
root.mainloop()

 

 

YouTube Downloader code in Python, Tkinter using ChatGPT

In this tutorial, I’ll create a YouTube Downloader using ChatGPT watch the video and try this Code.

Source Code is here:

import tkinter as tk
from tkinter import messagebox, ttk
from pytube import YouTube
import threading
import os
def download_video():
    video_url = url_entry.get()
    try:
        yt = YouTube(video_url)
        stream = yt.streams.get_highest_resolution()
        video_title = yt.title
        file_size = stream.filesize
        def download():
            stream.download(output_path=”C:/videos/”)
            messagebox.showinfo(“Success”, f”Video ‘{video_title}’ downloaded successfully!”)
        def update_progress():
            while stream.filesize > os.path.getsize(“C:/videos/” + stream.title + “.mp4”):
                bytes_downloaded = os.path.getsize(“C:/videos/” + stream.title + “.mp4”)
                percent = (bytes_downloaded / file_size) * 100
                progress_bar[‘value’] = percent  # Set the progress bar value directly
                root.update_idletasks()
            progress_bar[‘value’] = 100
            download()
        download_thread = threading.Thread(target=download)
        download_thread.start()
        progress_thread = threading.Thread(target=update_progress)
        progress_thread.start()
    except Exception as e:
        messagebox.showerror(“Error”, f”An error occurred: {str(e)}”)
# Create the main window
root = tk.Tk()
root.title(“YouTube Video Downloader”)
# Set the initial window size
root.geometry(“400×250”)  # Width x Height
# Create a custom style for the labels
label_style = ttk.Style()
label_style.configure(“CustomLabel.TLabel”, foreground=”#333″, font=(“Helvetica”, 12))
url_label = ttk.Label(root, text=”Enter YouTube URL:”, style=”CustomLabel.TLabel”)
url_label.pack(pady=10)
# Create a custom style for the entry widget
entry_style = ttk.Style()
entry_style.configure(“CustomEntry.TEntry”, font=(“Helvetica”, 12))
url_entry = ttk.Entry(root, width=40, style=”CustomEntry.TEntry”)
url_entry.pack(pady=10)
# Create a custom style for the buttons
button_style = ttk.Style()
button_style.configure(“CustomButton.TButton”, foreground=”black”, background=”#0074D9″, font=(“Helvetica”, 13))
download_button = ttk.Button(root, text=”Download”, command=download_video, style=”CustomButton.TButton”)
download_button.pack(pady=10)
# Create the progress bar
progress_bar = ttk.Progressbar(root, length=200, mode=’determinate’)
progress_bar.pack(pady=10)
root.mainloop()

Snake Game Python Code

How to Code Snake game Using Python, Tkinter with the help of ChatGPT.

Source Code Here
import tkinter as tk
import random
WIDTH = 400
HEIGHT = 400
SQUARE_SIZE = 20
class SnakeGame:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title(“Snake Game”)
        self.canvas = tk.Canvas(self.root, width=WIDTH, height=HEIGHT)
        self.canvas.pack()
        self.snake = [(100, 100)]
        self.food = self.generate_food()
        self.direction = “Right”
        self.root.bind(“<Key>”, self.change_direction)
        self.update()
    def generate_food(self):
        x = random.randint(0, (WIDTH – SQUARE_SIZE) // SQUARE_SIZE) * SQUARE_SIZE
        y = random.randint(0, (HEIGHT – SQUARE_SIZE) // SQUARE_SIZE) * SQUARE_SIZE
        return x, y
    def change_direction(self, event):
        if event.keysym in [“Up”, “Down”, “Left”, “Right”]:
            self.direction = event.keysym
    def move_snake(self):
        x, y = self.snake[0]
        if self.direction == “Up”:
            y -= SQUARE_SIZE
        elif self.direction == “Down”:
            y += SQUARE_SIZE
        elif self.direction == “Left”:
            x -= SQUARE_SIZE
        elif self.direction == “Right”:
            x += SQUARE_SIZE
        self.snake.insert(0, (x, y))
        if self.snake[0] == self.food:
            self.food = self.generate_food()
        else:
            self.snake.pop()
    def check_collision(self):
        x, y = self.snake[0]
        if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT or self.snake[0] in self.snake[1:]:
            return True
        return False
    def update(self):
        self.move_snake()
        if self.check_collision():
            self.canvas.create_text(WIDTH // 2, HEIGHT // 2, text=”Game Over”, font=(“Arial”, 20))
            return
        self.canvas.delete(“all”)
        self.canvas.create_rectangle(*self.food, self.food[0] + SQUARE_SIZE, self.food[1] + SQUARE_SIZE, fill=”red”)
        for x, y in self.snake:
            self.canvas.create_rectangle(x, y, x + SQUARE_SIZE, y + SQUARE_SIZE, fill=”green”)
        self.root.after(100, self.update)
    def run(self):
        self.root.mainloop()
if __name__ == “__main__”:
    game = SnakeGame()
    game.run()

Age Calculator Source Code

Age Calculator and Duration Calculator

Explore our free online tools – the Age Calculator and Duration Calculator, designed to simplify age calculations and date duration measurements. Whether you need to calculate your age in years, months, and days or find the duration between two dates in various units, our calculators provide quick and accurate results. Try the Age Calculator and Duration Calculator today on Imran.xyz!

[WP-Coder id=”1″]

[sourcecode language=”plain”]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Duration Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="dateCalculator">
<label for="startDate">Start Date:</label>
<input type="date" id="startDate" required>
<label for="endDate">End Date:</label>
<input type="date" id="endDate" required>
<button id="calculateBtn">Calculate Duration</button>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>

[/sourcecode]

CSS Code

  • [css autolinks=”false” classname=”myclass” collapse=”false” firstline=”1″ gutter=”true” highlight=”1-3,6,9″ htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”true” title=”example-filename.php”]

    &amp;amp;lt;/pre&amp;amp;gt;
    /* Updated CSS styles for the result */
    #dateCalculator {
    text-align: center;
    margin: 50px;
    }

    label {
    font-size: 18px;
    }

    input {
    padding: 5px;
    font-size: 16px;
    margin: 10px;
    }

    button {
    padding: 10px 20px;
    background-color: #007BFF;
    color: #fff;
    border: none;
    font-size: 16px;
    cursor: pointer;
    }

    button:hover {
    background-color: #0056b3;
    }

    #result {
    font-size: 20px;
    margin-top: 20px;
    text-align: center;
    }

    .result-line {
    font-size: 18px;
    margin: 10px 0;
    }

    .result-line:first-child {
    margin-top: 0;
    }

    .or {
    font-weight: bold;
    margin-right: 10px;
    }
    &amp;amp;lt;pre&amp;amp;gt;[/css]

 

Java Script (JS) Code

 

 

[code lang=”js”]</pre>
document.getElementById("calculateBtn").addEventListener("click", calculateDuration);

function calculateDuration() {
var startDate = new Date(document.getElementById("startDate").value);
var endDate = new Date(document.getElementById("endDate").value);

if (isNaN(startDate) || isNaN(endDate)) {
document.getElementById("result").innerHTML = "Please select valid dates.";
} else {
var durationInMilliseconds = endDate – startDate;
var durationInSeconds = durationInMilliseconds / 1000;
var durationInMinutes = durationInSeconds / 60;
var durationInHours = durationInMinutes / 60;
var durationInDays = durationInHours / 24;
var durationInWeeks = durationInDays / 7;
var durationInMonths = durationInDays / 30.4375; // An average month length
var durationInYears = durationInMonths / 12;

document.getElementById("result").innerHTML =
"<div class='result-line'>" +
"Duration: " +
Math.floor(durationInYears) + " years, " +
Math.floor(durationInMonths % 12) + " months, " +
Math.floor(durationInDays % 30) + " days</div>" +

"<div class='result-line'>" +
"<span class='or'>or</span>" +
Math.floor(durationInMonths) + " months " + Math.floor(durationInDays % 30) + " days</div>" +

"<div class='result-line'>" +
"<span class='or'>or</span>" +
Math.floor(durationInWeeks) + " weeks " + Math.floor(durationInDays % 7) + " days</div>" +

"<div class='result-line'>" +
"<span class='or'>or</span>" +
Math.floor(durationInDays) + " days</div>" +

"<div class='result-line'>" +
"<span class='or'>or</span>" +
Math.floor(durationInHours) + " hours</div>" +

"<div class='result-line'>" +
"<span class='or'>or</span>" +
Math.floor(durationInMinutes) + " minutes</div>" +

"<div class='result-line'>" +
"<span class='or'>or</span>" +
Math.floor(durationInSeconds) + " seconds</div>";
}
}
<pre>[/code]

 

Date Calculator Source Code

Are you looking to calculate the number of days between two important dates? Perhaps you need to plan an event, track project timelines, or simply satisfy your curiosity. Look no further! In this comprehensive guide, we’ll show you how to use a Date Calculator effectively and explore the many ways it can simplify your life.

[WP-Coder id=”2″]

 

HTML Code

[sourcecode language=”plain”]</h3>
<h3><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="dateCalculator">
<label for="startDate">Start Date:</label>
<input type="date" id="startDate" required>
<label for="endDate">End Date:</label>
<input type="date" id="endDate" required>
<button id="calculateBtn">Calculate Days</button>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html></h3>
<h3>[/sourcecode]

 

 

CSS Code

  • [sourcecode language=”plain”]</pre>
    /* CSS styles for the Date Calculator */
    #dateCalculator {
    text-align: center;
    margin: 50px;
    }

    label {
    font-size: 18px;
    }

    input {
    padding: 5px;
    font-size: 16px;
    margin: 10px;
    }

    button {
    padding: 10px 20px;
    background-color: #007BFF;
    color: #fff;
    border: none;
    font-size: 16px;
    cursor: pointer;
    }

    button:hover {
    background-color: #0056b3;
    }

    #result {
    font-size: 20px;
    margin-top: 20px;
    text-align: center;
    }

    .result-line {
    font-size: 18px;
    margin-bottom: 10px;
    }

    .result-line:first-child {
    margin-top: 0;
    }

    &nbsp;
    <pre>
    [/sourcecode]

 

Java Script (JS)  Code

  • [code lang=”js”]</pre>
    // JavaScript code for the Date Calculator
    document.getElementById("calculateBtn").addEventListener("click", calculateDays);

    function calculateDays() {
    var startDate = new Date(document.getElementById("startDate").value);
    var endDate = new Date(document.getElementById("endDate").value);

    if (isNaN(startDate) || isNaN(endDate)) {
    document.getElementById("result").innerHTML = "Please select valid dates.";
    } else {
    var timeDifference = endDate – startDate;
    var daysDifference = Math.floor(timeDifference / (1000 * 60 * 60 * 24));

    document.getElementById("result").innerHTML =
    "<div class='result-line'>" +
    "Days Between Dates: " + daysDifference + " days</div>";
    }
    }
    <pre>
    [/code]