Python - Create Guess The Word Game Using Tkinter

How To Make Guess The Word Game In Python Using Tkinter

Python Guess The Word Game


In this Python Tutorial we will see How to Make a Guess Word Game In Python Using Tkinter .

Steps:
- initializes a list of words to guess from.
- sets up the GUI components, including labels, textboxes, and buttons with their respective functions.
- Create The "displayWord" function to displays a word with some missing letters as underscores and randomly selects positions to hide letters.
Create The "checkWord" function to checks if the entered word in the textbox matches the current word being guessed and updates the result label accordingly (either "Correct" or "Wrong").
- The "Start" button initializes the game, disables itself, and enables the "Next" button for progression.
- The "Next" button checks the current word, updates the result, and proceeds to the next word.
- When all words have been guessed, the "Start" button is re-enabled to restart the game.





Project Source Code:


import tkinter as tk
from tkinter import *
from tkinter import Tk
import random

root = Tk()
root.title("Guess The Word Game")

words_list = ["driver","signature","history", "response","president","highway",
"computer", "appartment", "forest", "chocolat", "lawyer"]

index = -1

lbl_word = tk.Label(text="Word", font=("Verdana",20))
textbox = tk.Entry(text="Guess", font=("Verdana",20), justify="center")
btn_next = tk.Button(text="Next", font=("Verdana",20), state = "disabled",
bg="#2980b9", fg="#fff", command = lambda : btn_next_command())
btn_start = tk.Button(text="Start", font=("Verdana",20), bg="#2980b9",
fg="#fff", command = lambda : btn_start_command())
lbl_result = tk.Label(text="Result", font=("Verdana",20), bg="Grey", fg="#fff")

lbl_word.grid(row=0, column=0, sticky="nsew")
textbox.grid(row=1, column=0, sticky="nsew")
btn_next.grid(row=2, column=0, sticky="nsew")
btn_start.grid(row=3, column=0, sticky="nsew")
lbl_result.grid(row=4, column=0, sticky="nsew")



# create a function to display the word
def displayWord():
if index == -1:
lbl_word['text'] = "Word"
textbox.insert(INSERT, "Guess")
else:
text_val = words_list[index]
pos1 = random.randint(0, len(text_val))
pos2 = random.randint(0, len(text_val))
pos3 = random.randint(0, len(text_val))

text_val = text_val[:pos1] + "_" + text_val[pos1+1:]
text_val = text_val[:pos2] + "_" + text_val[pos2+1:]
text_val = text_val[:pos3] + "_" + text_val[pos3+1:]

lbl_word['text'] = text_val


# create a function to check if the word entred is correct
def checkWord():
if textbox.get() == words_list[index]:
lbl_result['text'] = "Correct"
lbl_result['bg'] = "Green"
else:
lbl_result['text'] = "Wrong"
lbl_result['bg'] = "Red"
if index == len(words_list) - 1:
btn_start['state'] = 'normal'
btn_next['state'] = 'disabled'

textbox.delete(0, END)



# create a function for the start button
def btn_start_command():
global index
index = 0
displayWord()
textbox.delete(0,END)
btn_start['state'] = 'disabled'
btn_next['state'] = 'normal'
lbl_result['text'] = ''
lbl_result['bg'] = 'Grey'


# create a function for the next button
def btn_next_command():
global index
checkWord()
if index < len(words_list) - 1:
index += 1
displayWord()




displayWord()

root.mainloop()

                                       

////// OUTPUT : 



Python Guess The Word Game Source Code

Create Guess The Word Game Using Python Tkinter

Guess The Word Game Using Python Tkinter

How To Make Guess The Word Game In Python Using Tkinter,

How To Create Guess The Word Game In Python Using Tkinter,




download the source code









Python And MySQL - Insert Update Delete Search And Display Data On Tkinter TreeView

How To Insert Update Delete And Show Records In TreeView Using Python Tkinter

Python And MySQL - Insert Update Delete Search And Display Data On Tkinter TreeView


In this Python Tkinter CRUD Tutorial With MySQL Database we will see How To:
- insert data in mysql database.
- remove selected record from mysql database.
- edit selected record from mysql database.
- search for a specific record by id.
- display mysql database records in a tkinter treeview.






Project Source Code:

import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import mysql.connector


connection = mysql.connector.connect(host='localhost', user='root', port='3306',
password='', database='test_py')
c = connection.cursor()

root = Tk()

frame = tk.Frame(root)
frame_btns = tk.Frame(frame)

label_id = tk.Label(frame, text="ID:", font=('verdana',14))
entry_id = tk.Entry(frame, font=('verdana',14))

label_fname = tk.Label(frame, text="First Name:", font=('verdana',14))
entry_fname = tk.Entry(frame, font=('verdana',14))

label_lname = tk.Label(frame, text="Last Name:", font=('verdana',14))
entry_lname = tk.Entry(frame, font=('verdana',14))

label_email = tk.Label(frame, text="Email:", font=('verdana',14))
entry_email = tk.Entry(frame, font=('verdana',14))

label_age = tk.Label(frame, text="Age:", font=('verdana',14))
entry_age = tk.Entry(frame, font=('verdana',14))

button_add = tk.Button(frame_btns, text="Add", font=('verdana',14), bg='green',
fg='#ffffff')
button_edit = tk.Button(frame_btns, text="Edit", font=('verdana',14), bg='blue',
fg='#ffffff')
button_remove = tk.Button(frame_btns, text="Remove", font=('verdana',14), bg='red',
fg='#ffffff')
button_search = tk.Button(frame_btns, text="Search", font=('verdana',14), bg='orange',
fg='#ffffff')

trv = ttk.Treeview(frame, columns=(1,2,3,4,5), height=15, show="headings")
trv.column(1, anchor=CENTER, stretch=NO, width=100)
trv.column(2, anchor=CENTER, stretch=NO, width=100)
trv.column(3, anchor=CENTER, stretch=NO, width=100)
trv.column(4, anchor=CENTER, stretch=NO, width=100)
trv.column(5, anchor=CENTER, stretch=NO, width=100)

trv.heading(1, text="ID")
trv.heading(2, text="First Name")
trv.heading(3, text="Last Name")
trv.heading(4, text="Email")
trv.heading(5, text="Age")

def add():
fname = entry_fname.get().strip() # remove white space
lname = entry_lname.get().strip()
email = entry_email.get().strip()
age = entry_age.get().strip()
vals = (fname,lname,email,age)

if(len(fname) > 0 and len(lname) > 0 and len(email) > 0 and int(age) > 10):
c.execute("INSERT INTO `users_2`(`firstname`, `lastname`, `email`, `age`)
VALUES (%s,%s,%s,%s)", vals)
connection.commit()
messagebox.showinfo('Add','User Info Has Been Added')
displayUsers()
else:
messagebox.showwarning('Add','Incorrrect Data')


def edit():
user_id = entry_id.get().strip()
fname = entry_fname.get().strip()
lname = entry_lname.get().strip()
email = entry_email.get().strip()
age = entry_age.get().strip()
if(len(fname) > 0 and len(lname) > 0 and len(email) > 0 and int(age) > 10):
vals = (fname,lname,email,age,user_id)
c.execute("UPDATE `users_2` SET `firstname`=%s,`lastname`=%s,`email`=%s,
`age`=%s WHERE `id`=%s", vals)
connection.commit()
messagebox.showinfo('Edit','User Info Has Been Edited')
displayUsers()
else:
messagebox.showwarning('Edit','Incorrrect Data')

def remove():
user_id = entry_id.get().strip()
c.execute("DELETE FROM `users_2` WHERE `id` = " + user_id)
connection.commit()
messagebox.showinfo('Delete','User Info Has Been Deleted')
displayUsers()

def search():
user_id = entry_id.get().strip()
c.execute("SELECT * FROM `users_2` WHERE `id` = " + user_id)
user = c.fetchone()
# clear fields
entry_fname.delete(0, END)
entry_lname.delete(0, END)
entry_email.delete(0, END)
entry_age.delete(0, END)
if user:
# display data
entry_fname.insert(0, user[1])
entry_lname.insert(0, user[2])
entry_email.insert(0, user[3])
entry_age.insert(0, user[4])
else:
messagebox.showwarning('User','No User Found')




def displayUsers():
# clear treeview
for row in trv.get_children():
trv.delete(row)
# populate treeview
c.execute("SELECT * FROM `users_2`")
users = c.fetchall()

for user in users:
trv.insert('', END, values=user)



button_add['command'] = add
button_edit['command'] = edit
button_remove['command'] = remove
button_search['command'] = search

displayUsers()

label_id.grid(row=0, column=0, sticky='e')
entry_id.grid(row=0, column=1)

label_fname.grid(row=1, column=0, sticky='e')
entry_fname.grid(row=1, column=1)

label_lname.grid(row=2, column=0, sticky='e')
entry_lname.grid(row=2, column=1)

label_email.grid(row=3, column=0, sticky='e')
entry_email.grid(row=3, column=1)

label_age.grid(row=4, column=0, sticky='e')
entry_age.grid(row=4, column=1)

frame_btns.grid(row=5, column=0, columnspan=2)
button_add.grid(row=0, column=0, padx=10, pady=10)
button_edit.grid(row=0, column=1, padx=10, pady=10)
button_remove.grid(row=0, column=2, padx=10, pady=10)
button_search.grid(row=0, column=3, padx=10, pady=10)


trv.grid(row=0, column=3, rowspan=5, padx=10, pady=10)

frame.grid(row=0, column=0)

root.mainloop()


///////////////OUTPUT:


Python Tkinter And MySQL - Insert Update Delete Search And Display

Python Tkinter And MySQL - Insert Update Delete Search And Display Records
Python Tkinter Insert Button To MySQL

Python Tkinter And MySQL - Insert Update Delete Search And Show Records
Python Insert Button To MySQL 2



if you want the source code click on the download button below













C# Products Manager Project With MySQL Database

How To Make a C# Products Manager Project With MySQL Database Using Visual Studio

C# Products Manager Project With MySQL Database


In This C# Tutorial  We Will See How To Create a Simple Products Manager Project With Windows Form Using Csharp Programming Language And MySQL Database.

- Add a New Product.
- Edit Selected Product.
- Remove Selected Product.
- Display a List Of Products.
- Search For a  Product.
- Navigate Between Products.



Project Source Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Products_Manager_App
{
    public partial class Management_Form : Form
    {
        public Management_Form()
        {
            InitializeComponent();
        }

        MySqlConnection connection = new MySqlConnection("datasource = localhost;port = 3306; initial catalog = csharp_products; username = root; password =");
        DataTable table = new DataTable();
        int productIndex = 0;

        // create a function to display products
        public void showProducts()
        {
            // clear the datatable first
            table.Clear();
            dataGridViewProducts.DataSource = table;

            MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM `product`", connection);
            adapter.Fill(table);
            dataGridViewProducts.DataSource = table;
            label_ProductsCount.Text = table.Rows.Count.ToString() + " Product";
        }
    
// the form load
        private void Management_Form_Load(object sender, EventArgs e)
        {
            // change DGV height
            dataGridViewProducts.RowTemplate.Height = 40;
            
            // display the close icon
            pictureBoxClose.Image = Properties.Resources.close;
            // display products on DGV
            showProducts();
            // select the first item in the combobox
            comboBoxCategories.SelectedIndex = 0;

            // customize DGV header
            dataGridViewProducts.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(47,54,64);
            dataGridViewProducts.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            dataGridViewProducts.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Verdana", 15, FontStyle.Italic);
            dataGridViewProducts.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewProducts.GridColor = Color.DarkBlue;
            dataGridViewProducts.AllowUserToAddRows = false;
            dataGridViewProducts.EnableHeadersVisualStyles = false;

        }
        
// picturebox to close the form and connection
        private void pictureBoxClose_Click(object sender, EventArgs e)
        {
            // close the connection
            if (ConnectionState.Open == connection.State)
            {
                connection.Close();
            }

            // close the app
            System.Environment.Exit(System.Environment.ExitCode);
        }

        // browse and display the image
        // + the image path
        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            opf.Filter = "Choose Image(*.jpg;*.png;*.gif)|*.jpg;*.png;*.gif";

            if(opf.ShowDialog() == DialogResult.OK)
            {
                pictureBoxProduct.Image = Image.FromFile(opf.FileName);
                textBoxImagePath.Text = opf.FileName;
            }
        }

// button insert a new product
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            try
            {
                string name = textBoxName.Text;
                string category = comboBoxCategories.Text;
                int quantity = int.Parse(textBoxQuantity.Text);
                float price = float.Parse(textBoxPrice.Text);
                string imagePath = textBoxImagePath.Text;

                MySqlCommand command = new MySqlCommand("INSERT INTO `product`(`name`, `category`, `quantity`, `price`, `picture`) VALUES (@nm,@ctg,@qty,@prc,@pic)", connection);

                command.Parameters.Add("@nm", MySqlDbType.VarChar).Value = name;
                command.Parameters.Add("@ctg", MySqlDbType.VarChar).Value = category;
                command.Parameters.Add("@qty", MySqlDbType.Int16).Value = quantity;
                command.Parameters.Add("@prc", MySqlDbType.Float).Value = price;
                command.Parameters.Add("@pic", MySqlDbType.VarChar).Value = imagePath;

                if (ConnectionState.Closed == connection.State)
                {
                    connection.Open();
                }

                if (command.ExecuteNonQuery() == 1)
                {
                    showProducts();
                    MessageBox.Show("The Product Has Been Added Successfully", "Product Added", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    MessageBox.Show("The Product Hasn't Been Added", "Product Not Added", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Enter The Product Info", "Empty Fileds", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        // display the selected product info
        private void dataGridViewProducts_Click(object sender, EventArgs e)
        {
            DataGridViewRow selectedRow = dataGridViewProducts.CurrentRow;

            numericUpDownID.Value = int.Parse(selectedRow.Cells[0].Value.ToString());
            textBoxName.Text = selectedRow.Cells[1].Value.ToString();
            comboBoxCategories.Text = selectedRow.Cells[2].Value.ToString();
            textBoxQuantity.Text = selectedRow.Cells[3].Value.ToString();
            textBoxPrice.Text = selectedRow.Cells[4].Value.ToString();
            textBoxImagePath.Text = selectedRow.Cells[5].Value.ToString();
            pictureBoxProduct.Image = Image.FromFile(selectedRow.Cells[5].Value.ToString());
        }

        // button update the selected product
        private void buttonEdit_Click(object sender, EventArgs e)
        {

            try
            {
                int id = (int)numericUpDownID.Value;
                string name = textBoxName.Text;
                string category = comboBoxCategories.Text;
                int quantity = int.Parse(textBoxQuantity.Text);
                float price = float.Parse(textBoxPrice.Text);
                string imagePath = textBoxImagePath.Text;

                MySqlCommand command = new MySqlCommand("UPDATE `product` SET `name`=@nm,`category`=@ctg,`quantity`=@qty,`price`=@prc,`picture`=@pic WHERE `id` = @id", connection);

                command.Parameters.Add("@nm", MySqlDbType.VarChar).Value = name;
                command.Parameters.Add("@ctg", MySqlDbType.VarChar).Value = category;
                command.Parameters.Add("@qty", MySqlDbType.Int16).Value = quantity;
                command.Parameters.Add("@prc", MySqlDbType.Float).Value = price;
                command.Parameters.Add("@pic", MySqlDbType.VarChar).Value = imagePath;
                command.Parameters.Add("@id", MySqlDbType.Int16).Value = id;

                if (ConnectionState.Closed == connection.State)
                {
                    connection.Open();
                }

                if (command.ExecuteNonQuery() == 1)
                {
                    showProducts();
                    MessageBox.Show("The Product Info Has Been Edited Successfully", "Edit Product", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    MessageBox.Show("The Product Info Hasn't Been Edited", "Product Not Edited", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Enter The Product Info", "Empty Fileds", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }



        }

        // button search product by id
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            try
            {
                int id = (int)numericUpDownID.Value;
                DataRow[] row = table.Select("id = " + id);

                if(row.Length > 0)
                {
                    textBoxName.Text = row[0][1].ToString();
                    comboBoxCategories.Text = row[0][2].ToString();
                    textBoxQuantity.Text = row[0][3].ToString();
                    textBoxPrice.Text = row[0][4].ToString();
                    textBoxImagePath.Text = row[0][5].ToString();
                    pictureBoxProduct.Image = Image.FromFile(row[0][5].ToString());
                }
                else
                {
                    textBoxName.Text = "";
                    comboBoxCategories.SelectedIndex = 0;
                    textBoxQuantity.Text = "";
                    textBoxPrice.Text = "";
                    textBoxImagePath.Text = "";
                    pictureBoxProduct.Image = null;
                    MessageBox.Show("No Product With This ID, Enter a New One", "Product Not found", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
                }

            }
            catch(Exception ex)
            {
                MessageBox.Show("Error -> " + ex.Message, "Product Not found", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            
        }

        // button remove product by id
        private void buttonRemove_Click(object sender, EventArgs e)
        {
            int id = (int)numericUpDownID.Value;

            MySqlCommand command = new MySqlCommand("DELETE FROM `product` WHERE `id` = @id", connection);

            command.Parameters.Add("@id", MySqlDbType.Int16).Value = id;

            if (ConnectionState.Closed == connection.State)
            {
                connection.Open();
            }

            if(MessageBox.Show("Are You Sure You Want To Remove This Product","Remove Product",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                if (command.ExecuteNonQuery() == 1)
                {
                    numericUpDownID.Value = 0;
                    textBoxName.Text = "";
                    comboBoxCategories.SelectedIndex = 0;
                    textBoxQuantity.Text = "";
                    textBoxPrice.Text = "";
                    textBoxImagePath.Text = "";
                    pictureBoxProduct.Image = null;
                    showProducts();
                    MessageBox.Show("Product Removed Successfully", "Remove Product", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Product NOT Removed", "Remove Product", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            

        }

        // button -> show the first item
        private void buttonFirst_Click(object sender, EventArgs e)
        {
            productIndex = 0;
            displayInfo(productIndex);
        }

        // button -> show the next item
        private void buttonNext_Click(object sender, EventArgs e)
        {
            productIndex ++;
            if (productIndex > table.Rows.Count - 1) { productIndex = table.Rows.Count - 1; }
            displayInfo(productIndex);
        }

        // button -> show the previous item
        private void buttonPrevious_Click(object sender, EventArgs e)
        {
            productIndex --;
            if (productIndex < 0) { productIndex = 0; }
            displayInfo(productIndex);
        }

        // button -> show the last item
        private void buttonLast_Click(object sender, EventArgs e)
        {
            productIndex = table.Rows.Count-1;
            displayInfo(productIndex);
        }

        // create a function to display info
        public void displayInfo(int index)
        {

            // select the DGV row
            dataGridViewProducts.ClearSelection();
            dataGridViewProducts.Rows[index].Selected = true; 

            numericUpDownID.Value = (int)table.Rows[index][0];
            textBoxName.Text = table.Rows[index][1].ToString();
            comboBoxCategories.Text = table.Rows[index][2].ToString();
            textBoxQuantity.Text = table.Rows[index][3].ToString();
            textBoxPrice.Text = table.Rows[index][4].ToString();
            textBoxImagePath.Text = table.Rows[index][5].ToString();
            pictureBoxProduct.Image = Image.FromFile(table.Rows[index][5].ToString());
        }

        // button to clear fields
        private void buttonClear_Click(object sender, EventArgs e)
        {
            numericUpDownID.Value = 0;
            textBoxName.Text = "";
            comboBoxCategories.SelectedIndex = 0;
            textBoxQuantity.Text = "";
            textBoxPrice.Text = "";
            textBoxImagePath.Text = "";
            pictureBoxProduct.Image = null;
        }

// allow only numbers in textboxquantity
        private void textBoxQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            // allow only numbers
            // you can use a numericupdown
            // or a maskedtextbox
            if(!Char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

// allow only float in textboxprice
        private void textBoxPrice_KeyUp(object sender, KeyEventArgs e)
        {
            // allow the user to enter values that can be converted to float
            // else remove the text

            try
            {
                float price = float.Parse(textBoxPrice.Text);
            }
            catch(Exception ex)
            {
                MessageBox.Show("Enter a Valid Price ( " + ex.Message + " )","Invalid Price",MessageBoxButtons.OK,MessageBoxIcon.Error);
                textBoxPrice.Text = "";
            }

        }

    }
}



      
///////////////OUTPUT:

C# Project With MySQL Database