'StringVar' obj is not callable - string

it said the stringvar obj is not callable? i dont know how to fix this can someone help me. thanks
import sqlite3
from tkinter import *
from tkinter import messagebox
i use self.Username etc with a first letter capslock so i can pass it on database connection but it said that stringvar is not callable.
class register:
def __init__(self, window):
self.Username = StringVar()
self.Password = StringVar()
self.Confirm_Password = StringVar()
self.Fullname = StringVar()
self.window = window
self.window.geometry('500x200')
window.resizable(0, 0)
window.configure(bg="deep sky blue")
window.title("Register")
l1 = Label(self.window, text="Username:", font=("Arial", 15), bg="deep sky blue")
l1.place(x=10, y=10)
self.fullname = Entry(self.window, width=30, bd=5, textvariable=self.Fullname)
self.fullname.place(x=200, y=10)
l1 = Label(self.window, text="Username:", font=("Arial", 15), bg="deep sky blue")
l1.place(x=10, y=60)
self.username = Entry(self.window, width=30, bd=5, textvariable=self.Username)
self.username.place(x=200, y=60)
l2 = Label(self.window, text="Password:", font=("Arial", 15), bg="deep sky blue")
l2.place(x=10, y=110)
self.password = Entry(self.window, width=30, show="*", bd=5, textvariable=self.Password)
self.password.place(x=200, y=110)
l3 = Label(self.window, text="Confirm Password:", font=("Arial", 15), bg="deep sky blue")
l3.place(x=10, y=170)
self.confirm_password = Entry(self.window, width=30, show="*", bd=5, textvariable=self.Confirm_Password)
self.confirm_password.place(x=200, y=170)
b1 = Button(self.window, text="Sign in", font=("Arial", 15), bg="#ffc22a", command=self.submit)
b1.place(x=170, y=150)
b2 = Button(self.window, text="Back", font=("Arial", 15), bg="#ffc22a", command=self.submit)
b2.place(x=250, y=150)
heres how i pass it did i make mistake on passing the variable?
connection = sqlite3.connect('RegLog.db')
cur = connection.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS RegLog( username TEXT, Password TEXT, "
"ConfirmPassword TEXT)")
connection.commit()
connection.close()
def submit(self):
check_counter = 0
warn = ""
if self.fullname.get() == "":
warn = "Full Name can't be empty"
else:
check_counter += 1
if self.username.get() == "":
warn = "Full Name can't be empty"
else:
check_counter += 1
if self.password.get() == "":
warn = "Email Field can't be empty"
else:
check_counter += 1
if self.confirm_password.get() == "":
warn = "Sorry, can't sign up make sure all fields are complete"
else:
check_counter += 1
if self.password.get() != self.confirm_password.get():
warn = "Passwords didn't match!"
if check_counter == 4:
try:
connection = sqlite3.connect("RegLog.db")
cur = connection.cursor()
cur.execute("INSERT INTO RegLog values(?,?,?)",
(self.Username.get(), self.Password.get(), self.Confirm_Password.get(), self.Fullname()))
connection.commit()
connection.close()
messagebox.showinfo("Success", "New account created successfully")
and also i think this exception is thrown whenever run the program.it said expected type 'str|None',got 'Exception' instead
except Exception as ep:
messagebox.showerror('Error1', ep)
else:
messagebox.showerror('Error', warn)
def page():
window = Tk()
register(window)
window.mainloop()

Related

How to check multiple sites for availability at the same time

I wanted to write a code that will check the availability of sites using "status_code"
But in the end I got into a stupor, I do not know how to implement the verification of each site entered into the widgets
I manage to check only one site from one widget, but I need to check each one, and set a time for each site to check
I would like to know, or at least get hints on how to implement it
I will be grateful for any help
My attempt:
import tkinter as tk
from tkinter import ttk
import requests
import time
from tkinter import *
from tkinter import messagebox
window = Tk()
window.geometry('400x700')
window.title("SiteChecker")
def SiteCheck():
res=int(tim1.get())
Site_Value = txt1.get()
Get_Response = requests.get(Site_Value)
time.sleep(res)
if Get_Response.status_code != 200:
#as I understand it, you need to make a "for" loop, but I don't understand how to implement
def clicked():
txt = Entry(window, width=18)
txt.grid(column=0, pady=8)
txt_row = txt.grid_info()['row']
tim = Entry(window, width=3)
tim.grid(row=txt_row, column=1, pady=8)
lbl1 = Label(window, text="Enter references:")
lbl1.grid(column=0, row=1)
lbl2 = Label(window, text="Enter the test time: ")
lbl2.grid(column=1, row=1)
lbl3 = Label(window, text="Availability status ")
lbl3.grid(column=2, row=1)
txt1 = Entry(window,width=18)
txt1.grid(column=0, row=2, pady=8)
txt2 = Entry(window,width=18)
txt2.grid(column=0, row=3,pady=8)
txt3 = Entry(window,width=18)
txt3.grid(column=0, row=4,pady=8)
txt4 = Entry(window,width=18)
txt4.grid(column=0, row=5,pady=8)
txt5 = Entry(window,width=18)
txt5.grid(column=0, row=6,pady=8)
tim1 = Entry(window,width=3)
tim1.grid(column=1, row=2, pady=8)
tim2 = Entry(window,width=3)
tim2.grid(column=1, row=3, pady=8)
tim3 = Entry(window,width=3)
tim3.grid(column=1, row=4, pady=8)
tim4 = Entry(window,width=3)
tim4.grid(column=1, row=5, pady=8)
tim5 = Entry(window,width=3)
tim5.grid(column=1, row=6, pady=8)
result1 = Label(window,text="status")
result1.grid(column=2, row=2, pady=8)
result2 = Label(window,text="status")
result2.grid(column=2, row=3, pady=8)
result3 = Label(window,text="status")
result3.grid(column=2, row=4, pady=8)
result4 = Label(window,text="status")
result4.grid(column=2, row=5, pady=8)
result5 = Label(window,text="status")
result5.grid(column=2, row=6, pady=8)
btn = Button(window, text="Add another site", command=clicked)
btn.grid(column=1, row = 0)
Check_Button = Button(
window,
command = SiteCheck,
text='Start checking',
)
Check_Button.grid(row=0, column=2)
window.mainloop()
try this but i am do it without time sleep you can add later
import tkinter as tk
from tkinter import ttk
import requests
import time
from tkinter import *
from tkinter import messagebox
data_list = []
window = Tk()
window.geometry('400x700')
window.title("SiteChecker")
def set_input(obj, value):
obj.delete(1.0, "END")
obj.insert("END", value)
def SiteCheck():
#res=int(tim1.get())
#time.sleep(res)
for data in data_list:
url = data[0].get()
status = data[2]
if not str(url).startswith('http'):
continue
print(url)
Get_Response = None
try:
Get_Response = requests.get(url)
except:
status.config(text = 'status bad')
continue
if Get_Response.status_code == 200:
status.config(text = 'status ok')
pass
#as I understand it, you need to make a "for" loop, but I don't understand how to implement
else:
status.config(text = 'status bad')
def clicked():
txt = Entry(window, width=18)
txt.grid(column=0, pady=8)
txt_row = txt.grid_info()['row']
tim = Entry(window, width=3)
tim.grid(row=txt_row, column=1, pady=8)
txt_row = tim.grid_info()['row']
result1 = Label(window,text="status")
result1.grid(row=txt_row, column=2, pady=8)
data_list.append([txt, tim, result1])
lbl1 = Label(window, text="Enter references:")
lbl1.grid(column=0, row=1)
lbl2 = Label(window, text="Enter the test time: ")
lbl2.grid(column=1, row=1)
lbl3 = Label(window, text="Availability status ")
lbl3.grid(column=2, row=1)
for loop in range(2 ,6):
txt1 = Entry(window,width=18)
txt1.grid(column=0, row=loop, pady=8)
tim1 = Entry(window,width=3)
tim1.grid(column=1, row=loop, pady=8)
result1 = Label(window,text="status")
result1.grid(column=2, row=loop, pady=8)
data_list.append([txt1, tim1, result1])
btn = Button(window, text="Add another site", command=clicked)
btn.grid(column=1, row = 0)
Check_Button = Button(
window,
command = SiteCheck,
text='Start checking',
)
Check_Button.grid(row=0, column=2)
window.mainloop()

Score board from database with tkinter and SQLite

I've been adding a little extra functionality to a sample snake game which I downloaded from git hub but have hit a bit of a brick wall with regard to the score board. At the moment the extras I've added are:
A username entry and validation at the start of the game
Username displayed as the game is playing
Username and score are written to a database at the end of the game
A leaderboard is displayed at the end of the game
At the moment my leaderboard only pulls the data from the database and displays it in a label. Ideally I want it to read all of the data into some kind of data structure and only display the top 15 scores after a sort is performed on the records. Is there a relatively simple way to achieve this at all?
Here is my code so far:
import sqlite3
import tkinter as tk
from random import randint
from PIL import Image, ImageTk
from tkinter import messagebox, END
from sqlalchemy import create_engine
MOVE_INCREMENT = 20
MOVES_PER_SECOND = 15
GAME_SPEED = 1000 // MOVES_PER_SECOND
class Snake(tk.Canvas):
def __init__(self, parent, username):
self.username = username
super().__init__(
parent, width=600, height=620, background="black", highlightthickness=0
)
# Rest of the Snake class code goes here
self.snake_positions = [(100, 100), (80, 100), (60, 100)]
self.food_position = self.set_new_food_position()
self.direction = "Right"
self.score = 0
self.load_assets()
self.create_objects()
self.bind_all("<Key>", self.on_key_press)
self.pack()
self.after(GAME_SPEED, self.perform_actions)
def load_assets(self):
try:
self.snake_body_image = Image.open("./assets/snake.png")
self.snake_body = ImageTk.PhotoImage(self.snake_body_image)
self.food_image = Image.open("./assets/food.png")
self.food = ImageTk.PhotoImage(self.food_image)
except IOError as error:
print(error)
root.destroy()
def create_objects(self):
self.create_text(45, 12, text=f"Score: {self.score}", tag="score", fill="#fff", font=(10))
self.create_text(490, 12, text=f"Username: {self.username}", tag="username", fill="#fff", font=(10))
for x_position, y_position in self.snake_positions:
self.create_image(
x_position, y_position, image=self.snake_body, tag="snake"
)
self.create_image(*self.food_position, image=self.food, tag="food")
self.create_rectangle(7, 27, 593, 613, outline="#525d69")
def check_collisions(self):
head_x_position, head_y_position = self.snake_positions[0]
return (
head_x_position in (0, 600)
or head_y_position in (20, 620)
or (head_x_position, head_y_position) in self.snake_positions[1:]
)
def check_food_collision(self):
if self.snake_positions[0] == self.food_position:
self.score += 1
self.snake_positions.append(self.snake_positions[-1])
self.create_image(
*self.snake_positions[-1], image=self.snake_body, tag="snake"
)
self.food_position = self.set_new_food_position()
self.coords(self.find_withtag("food"), *self.food_position)
score = self.find_withtag("score")
self.itemconfigure(score, text=f"Score: {self.score}", tag="score")
def end_game(self):
self.delete(tk.ALL)
self.create_text(
self.winfo_width() / 2,
self.winfo_height() / 2,
text=f"Game over! You scored {self.score}!",
fill="#fff",
font=("", 8)
)
def write_to_database(self):
try:
# Open the Score Database
connection = sqlite3.connect("ScoreDatabase.db")
cursor = connection.cursor()
UserRec = []
UserRec.append(self.username)
UserRec.append(self.score)
# SQL statement to insert the user record into the Gamers table
buffer = "INSERT INTO Gamers VALUES (?, ?)"
cursor.execute(buffer, (self.username, self.score))
connection.commit()
connection.close()
except sqlite3.Error as e:
print("An error occurred:", e.args[0])
connection.close()
# End of new database code
def show_database_entries(self):
try:
con = sqlite3.connect("ScoreDatabase.db")
cur = con.cursor()
# Show all rows in the database
buffer = "SELECT * FROM Gamers;"
buffer = buffer.strip()
cur.execute(buffer)
rows = cur.fetchall()
count = 0
print()
print("Database entries -Username Score")
for x in rows:
print(str(x[0]) + ": " + str(x[1]))
count += 1
print()
con.commit()
con.close()
except sqlite3.Error as e:
print("An error occurred:", e.args[0])
connection.close()
def move_snake(self):
head_x_position, head_y_position = self.snake_positions[0]
if self.direction == "Left":
new_head_position = (head_x_position - MOVE_INCREMENT, head_y_position)
elif self.direction == "Right":
new_head_position = (head_x_position + MOVE_INCREMENT, head_y_position)
elif self.direction == "Down":
new_head_position = (head_x_position, head_y_position + MOVE_INCREMENT)
elif self.direction == "Up":
new_head_position = (head_x_position, head_y_position - MOVE_INCREMENT)
self.snake_positions = [new_head_position] + self.snake_positions[:-1]
for segment, position in zip(self.find_withtag("snake"), self.snake_positions):
self.coords(segment, position)
def on_key_press(self, e):
new_direction = e.keysym
all_directions = ("Up", "Down", "Left", "Right")
opposites = ({"Up", "Down"}, {"Left", "Right"})
if (
new_direction in all_directions
and {new_direction, self.direction} not in opposites
):
self.direction = new_direction
def perform_actions(self):
if self.check_collisions():
self.end_game()
self.write_to_database()
show_leaderboard()
self.check_food_collision()
self.move_snake()
self.after(GAME_SPEED, self.perform_actions)
def set_new_food_position(self):
while True:
x_position = randint(1, 29) * MOVE_INCREMENT
y_position = randint(3, 30) * MOVE_INCREMENT
food_position = (x_position, y_position)
if food_position not in self.snake_positions:
return food_position
root = tk.Tk()
root.title("Snake")
root.withdraw() # Hide root window for now
def StartGame():
username = UsernInput.get()
if len(username) > 8:
messagebox.showwarning("Invalid username", "Please enter a username of 8 characters or less")
window.focus()
else:
window.destroy() # Get rid of the username input
root.deiconify() # Show the root window again
root.tk.call("tk", "scaling", 4.0)
root.resizable(False, False)
board = Snake(root, username)
return username
def show_leaderboard():
leaderboard = tk.Toplevel()
leaderboard.focus
leaderboard.title("Leaderboard")
leaderboard.geometry('400x500')
leaderboard['bg'] = 'black'
leaderboard.tk.call("tk", "scaling", 4.0)
leaderboard.resizable(False, False)
Usern_label = tk.Label(leaderboard, text="High Scores", font=("Arial Bold", 12))
Usern_label.place(x=10, y=15)
Usern_label.config(fg="yellow")
Usern_label.config(bg="black")
my_con = sqlite3.connect('ScoreDatabase.db')
cursor = my_con.cursor()
cursor.execute("SELECT *, oid FROM Gamers LIMIT 15")
data = cursor.fetchall()
showData = ''
for data in data:
showData = showData.replace("'", "")
showData = showData.replace(",", "")
showData = showData.replace("(", "")
showData = showData.replace(")", "")
showData += str(data) + "\n"
results = tk.Label(leaderboard, text=showData, justify='left', width=15, font=("Arial", 6))
results.place(x=0, y=85)
results.config(fg="white")
results.config(bg="black")
my_con.commit()
my_con.close()
# New database code
#Create or open the Score Database * This works fine
connection = sqlite3.connect("ScoreDatabase.db")
cursor = connection.cursor()
# SQL statement to create the table structure of the Scoredatabase
try:
# following code runs once to create a new database named above
buffer ="CREATE TABLE IF NOT EXISTS Gamers (Username, Score, primary key(Username));"
buffer = buffer.strip()
cursor.execute(buffer)
connection.commit()
except sqlite3.Error as e:
print("An error occurred:", e.args[0])
connection.close()
# End of new database code
window = tk.Toplevel()
window.title("Snake game")
window.geometry('300x175')
window['bg']='black'
Instructions_label = tk.Label(window, bg='black', text="Enter your username to be entered into the score database. Usernames must be 8 characters or less ", wraplength=300, justify='left', font=("Arial Bold", 12))
Instructions_label.place(x=10, y=10)
Instructions_label.config(fg="#FFFFFF")
Instructions_label.config(bg="black")
Usern_label= tk.Label(window, bg='black', text="Username: ", font=("Arial Bold", 12))
Usern_label.place(x=10, y=90)
Usern_label.config(fg="#FFFFFF")
Usern_label.config(bg="black")
UsernInput = tk.Entry(window, bg='White', bd=1, width=20, highlightthickness=2)
UsernInput.place(x=110, y=90)
UsernInput.config(highlightbackground = "yellow", highlightcolor= "yellow")
usern_button = tk.Button(window, text='Start Game', bd='3', command=StartGame)
usern_button.place(x=20, y=130)
root.mainloop()

how to delete a specific item in the list after a button is clicked in tkinter python

Below is a small code where if you click add button a pop-up will appear where you write desired number. The number in the bottom represents the sum of all numbers you entered.
What I am trying to achieve is to update the sum_lbl and index_no as I delete any of the labels.
Code:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = []
index_no = 0
def destroy(widget):
widget.destroy()
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
while True:
def ok_():
global index_no
name = add_room_area_var.get()
index_no += 1
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=index_no)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:destroy(entry_frame))
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
area_lst.append(int(name))
add_room_area.destroy()
area_sum = sum(area_lst)
sum_lbl.config(text=area_sum)
break
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
Output:
After deleting the 3rd and 4th label the output is:
I would suggest to change area_lst to dictionary using the frame as the key and the two labels as the value for each row.
Then update destroy() to use area_lst to update the total and indexes:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = {} # dictionary to hold labels of each row using frame as the key
def destroy(frame):
frame.destroy()
del area_lst[frame]
update_total()
# update index of remaining rows
for idx, (lbl, _) in enumerate(area_lst.values(), 1):
lbl['text'] = idx
# function to update the total label
def update_total():
area_sum = sum(int(room['text']) for _, room in area_lst.values())
sum_lbl.config(text=area_sum)
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
def ok_():
name = add_room_area_var.get()
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=len(area_lst)+1)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:destroy(entry_frame))
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
# store current row to area_lst
area_lst[entry_frame] = (index_lbl, add_room_lbl)
add_room_area.destroy()
update_total()
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
You can allow buttons to call multiple commands, so for your 'close_button' button, I added two more commands: remove the name from 'area_lst' and update the 'sum_lbl' text with the new sum for 'area_lst'
Like this:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = []
index_no = 0
def destroy(widget):
widget.destroy()
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
while True:
def ok_():
global index_no
name = add_room_area_var.get()
index_no += 1
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=index_no)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:[destroy(entry_frame), area_lst.remove(int(name)), sum_lbl.config(text=sum(area_lst))])
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
area_lst.append(int(name))
add_room_area.destroy()
area_sum = sum(area_lst)
sum_lbl.config(text=area_sum)
break
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()

How to get Get value of check button in python tkinter library?

I've created a travel form in which a user will submit name, city, gender, phone number etc. Also, I've created a check button so that a user wants a meal he can tick on the check button.
My Question is How to get values of the Check button if the user has ticked the meal query written in the code.
Can anyone explain to me the logic on how to get the value of the Check button if the user has ticked on it?
from tkinter import *
root = Tk()
root.geometry('800x800')
def b():
print('Name is', namevalue.get()),
print('Phone number is', phonevalue.get())
print('Gender is', gendervalue.get()),
print('Extra Phone number is', phone1value.get()),
print('City is', cityvalue.get())
print('Food is required', )
f1 = Frame(root, bg = 'red', borderwidth = 8, relief = SUNKEN)
f1.grid()
Label(f1, text = 'Welcome to travel agency', pady = 5).grid(row = 0, column = 3)
#Making Widgets or we may call headers
name = Label(root, text = 'name')
phone = Label(root, text = 'Phone')
gender = Label(root, text = 'Enter your gender')
phone1 = Label(root, text = 'Extra Number')
city = Label(root, text = 'Your City')
name.grid(row = 1,column = 0)
phone.grid(row = 2,column = 0)
gender.grid(row = 3, column = 0)
phone1.grid(row = 4, column = 0)
city.grid(row = 5, column = 0)
#Assigining the headers a variable type
namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
phone1value = StringVar()
cityvalue = StringVar()
foodservicevalue = IntVar()
nameentry = Entry(root, textvariable = namevalue)
phoneentry = Entry(root, textvariable = phonevalue)
genderentry = Entry(root, textvariable = gendervalue)
cityentry = Entry(root, textvariable = cityvalue)
phone1entry = Entry(root, textvariable = phone1value)
nameentry.grid(row = 1, column = 3)
phoneentry.grid(row = 2, column = 3)
genderentry.grid(row = 3, column = 3)
phone1entry.grid(row = 4, column = 3)
cityentry.grid(row = 5, column = 3)
#Creating Check Button checkbutton
foodservicevalue = Checkbutton(text ='Do you wan\'t any meals', variable = foodservicevalue)
foodservicevalue.grid(row = 6, column = 3, padx = 1)
#Button and packing with assiginn
Button(text = 'Submit', command = b).grid(row = 7, column = 3)
root.mainloop()
This code works:
from tkinter import *
root = Tk()
root.geometry('800x800')
def b():
print('Name is', namevalue.get()),
print('Phone number is', phonevalue.get())
print('Gender is', gendervalue.get()),
print('Extra Phone number is', phone1value.get()),
print('City is', cityvalue.get())
if food_required.get() == 1:
print("Food is required.")
elif food_required.get() == 0:
print("Food is not required.")
# When the check button is clicked, then the value is 1 and it can be get using the .get() function.
# Similarly when the check button is not clicked then the value is 0.
f1 = Frame(root, bg='red', borderwidth=8, relief=SUNKEN)
f1.grid()
Label(f1, text='Welcome to travel agency', pady=5).grid(row=0, column=3)
# Making Widgets or we may call headers
name = Label(root, text='name')
phone = Label(root, text='Phone')
gender = Label(root, text='Enter your gender')
phone1 = Label(root, text='Extra Number')
city = Label(root, text='Your City')
name.grid(row=1, column=0)
phone.grid(row=2, column=0)
gender.grid(row=3, column=0)
phone1.grid(row=4, column=0)
city.grid(row=5, column=0)
# Assigining the headers a variable type
namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
phone1value = StringVar()
cityvalue = StringVar()
food_required = IntVar()
nameentry = Entry(root, textvariable=namevalue)
phoneentry = Entry(root, textvariable=phonevalue)
genderentry = Entry(root, textvariable=gendervalue)
cityentry = Entry(root, textvariable=cityvalue)
phone1entry = Entry(root, textvariable=phone1value)
nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
phone1entry.grid(row=4, column=3)
cityentry.grid(row=5, column=3)
# Creating Check Button #cHECKBUTTON
foodservicevalue = Checkbutton(text='Do you wan\'t any meals', variable=food_required)
foodservicevalue.grid(row=6, column=3, padx=1)
# Button and packing with assiginn
Button(text='Submit', command=b).grid(row=7, column=3)
root.mainloop()
When I saw your code, I found that you have used the variable foodservicevalue as an IntVar() and Checkbutton. I have used the if else statements to fix your issue.
This is #AmeyVijeesh's code but I removed the StringVars:
from tkinter import *
def b():
print("Name is", nameentry.get()),
print("Phone number is", phoneentry.get())
print("Gender is", genderentry.get()),
print("Extra Phone number is", phone1entry.get()),
print("City is", cityentry.get())
if food_required.get() == 1:
print("Food is required.")
elif food_required.get() == 0:
print("Food is not required.")
root = Tk()
root.geometry("800x800")
f1 = Frame(root, bg="red", borderwidth=8, relief="sunken")
f1.grid()
label = Label(f1, text="Welcome to travel agency", pady=5)
label.grid(row=0, column=3)
# Making Widgets or we may call headers
name = Label(root, text="Name")
phone = Label(root, text="Phone")
gender = Label(root, text="Enter your gender")
phone1 = Label(root, text="Extra Number")
city = Label(root, text="Your City")
name.grid(row=1, column=0)
phone.grid(row=2, column=0)
gender.grid(row=3, column=0)
phone1.grid(row=4, column=0)
city.grid(row=5, column=0)
# Assigining the headers a variable type
food_required = IntVar()
nameentry = Entry(root)
phoneentry = Entry(root)
genderentry = Entry(root)
cityentry = Entry(root)
phone1entry = Entry(root)
nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
phone1entry.grid(row=4, column=3)
cityentry.grid(row=5, column=3)
# Creating Check Button #cHECKBUTTON
foodservicevalue = Checkbutton(text="Do you want any meals", variable=food_required)
foodservicevalue.grid(row=6, column=3, padx=1)
# Button and packing with assiginn
button = Button(text="Submit", command=b)
button.grid(row=7, column=3)
root.mainloop()
Using <tkinter.Entry>.get() is much simpler than creating StringVars and assigning them to the <tkinter.Entry>s

OptionMenu in tkinter (python) is not showing the selected option or the default option

I am trying to create a python program to create the code for another python program. i have been learning python over the past week using a book (learn python in 24 hrs by katie cunningham) and also numerous online sources. i have run into a problem with the OptionMenu in tkinter where, it does not show the selected option or the default option (i used variable.set("defaultvalue")). i know that the program might be very inefficient, so please go easy on me. also if i dont provide option.config(width="14") the widget stays small.(please see the var_create_fn() function)
ive tried reinstalling pycharm and also python.
from tkinter import *
# from PIL import Image,ImageTk
from tkinter.messagebox import showinfo
window = Tk()
window.geometry('650x520')
window.title("Sash's CodeBuilder (feat.Python)")
main_label = Label(window, text="CodeBuilder Alpha", fg="indigo", bg="white", relief=SOLID, font=("arial", 30, "bold", "italic"))
main_label.pack(fill=BOTH, padx=3, pady=3)
# Variable declarations
printable = StringVar()
variable = StringVar()
varVal = StringVar()
varTypeSet = StringVar()
varTypes = ["String", "Integer"]
dataTypes = ["int", "float", "String", "list", "eval"]
dataTypeSet = StringVar()
inText = StringVar()
inVar = StringVar()
forVar = StringVar()
forPar = StringVar()
rangeChk = IntVar()
# FUNCTIONS
def printer():
showinfo(title="Printer", message="Printed.")
code = open("D:\\file.py", "a")
code.write("print(" + printable.get() + ")") & code.write("\n")
def var_create_fn():
window2 = Tk()
window2.geometry('150x100')
window2.title("Data Type Select")
window2_label = Label(window2, text="Select a data type :", bg="white", relief=SOLID, font=("arial", 10))
window2_label.pack(fill=BOTH, padx=3, pady=3)
var_data_type_box = OptionMenu(window2, varTypeSet, *varTypes)
var_data_type_box.config(width="14")
varTypeSet.set("select data type")
var_data_type_box.place(x=10, y=30)
but = Button(window2, text="Print", command=var_create_sub, font=("arial", 9, "bold"), bg="#44ff4c", fg="Blue")
but.place(x=55, y=70)
window2.mainloop()
def var_create():
if varVal.get() == "Enter variable value":
var_create_fn()
else:
showinfo(title="Variable creation", message="Variable with specified value created")
code = open("D:\\file.py", "a")
code.write(variable.get() + "=" + varVal.get()) & code.write("\n")
def var_create_sub():
global var1
var1 = varTypeSet.get()
if var1 == "String":
showinfo(title="Variable creation", message="Variable with specified value created")
code = open("D:\\file.py", "a")
code.write(variable.get() + " = StringVar()") & code.write("\n")
elif var1 == "Integer":
showinfo(title="Variable creation", message="Variable with specified value created")
code = open("D:\\file.py", "a")
code.write(variable.get() + " = IntVar()") & code.write("\n")
exit()
else:
showinfo(title="Variable creation", message="please select a value :")
def in_create():
create_data_type = dataTypeSet.get()
if create_data_type == "Select Data type":
showinfo(title="error", message="Empty field")
elif create_data_type != "String":
showinfo(title="Input creation", message="Input Code,, with specified data type and variable created")
code = open("D:\\file.py", "a")
code.write(inVar.get() + "=" + create_data_type+'(input("'+inText.get()+'"))') & code.write("\n")
else:
showinfo(title="Input creation", message="Input Code,, with specified data type and variable created")
code = open("D:\\file.py", "a")
code.write(inVar.get() + '=input("' + inText.get() + '")') & code.write("\n")
def for_create():
showinfo(title="For loop created", message="For loop with specified variable and parameters created.")
if rangeChk.get() == 1:
code = open("D:\\file.py", "a")
code.write("for " + forVar.get() + " in range(" + forPar.get() + "):") & code.write("\n")
else:
code = open("D:\\file.py", "a")
code.write("for " + forVar.get() + " in " + forPar.get() + ":") & code.write("\n")
# PROGRAM EXIT
btx = Button(window, text="Exit", command=exit, relief=SOLID, font=("arial", 14, "bold"))
btx.place(x=300, y=470)
# FOR PRINTING SOMETHING
# print label
printLabel = Label(window, text="Enter text to print :", bg="white", relief=SOLID, font=("arial", 10))
printLabel.place(x=5, y=58)
# text box
printBox = Entry(window, textvar=printable)
printBox.place(x=124, y=60)
# Print button
bt1 = Button(window, text="Print", command=printer, relief=RIDGE, font=("arial", 9, "bold"), bg="#44ff4c", fg="Blue")
bt1.place(x=250, y=57)
# CREATING A VARIABLE
# Variable label
varLabel = Label(window, text="Create a variable :", bg="white", relief=SOLID, font=("arial", 10))
varLabel.place(x=5, y=84)
# Variable Box
varBox = Entry(window, textvar=variable)
varBox.insert(END, "Enter variable name")
varBox.place(x=124, y=87)
# Variable value box
varValBox = Entry(window, textvar=varVal)
varValBox.insert(0, "Enter variable value")
varValBox.place(x=254, y=87)
# Variable Button
bt2 = Button(window, text="Create", relief=RIDGE, command=var_create, font=("arial", 9, "bold"), bg="#44ff4c", fg="Blue")
bt2.place(x=380, y=82)
# CREATING INPUT CODE
# Input label
inLabel = Label(window, text="Create input Code:", bg="white", relief=SOLID, font=("arial", 10))
inLabel.place(x=5, y=110)
# Data type combo box
inDataType = OptionMenu(window, dataTypeSet, *dataTypes)
dataTypeSet.set("Select Data type")
inDataType.config(width="14")
inDataType.place(x=122, y=107)
# Input text box
inTextBox = Entry(window, textvar=inText)
inTextBox.insert(0, "Enter input text")
inTextBox.place(x=254, y=113)
# Input variable box
inVarBox = Entry(window, textvar=inVar)
inVarBox.insert(0, "Enter input variable")
inVarBox.place(x=382, y=113)
# Input Button
b3 = Button(window, text="Create", relief=RIDGE, command=in_create, font=("arial", 9, "bold"), bg="#44ff4c", fg="Blue")
b3.place(x=508, y=110)
# FOR LOOP
# For Loop label
forLabel = Label(window, text=" Create For loop:", bg="white", relief=SOLID, font=("arial", 10))
forLabel.place(x=5, y=136)
# For Variable box
forVarBox = Entry(window, textvar=forVar)
forVarBox.insert(0, "Enter loop variable")
forVarBox.place(x=124, y=139)
# For Loop parameters box
forParBox = Entry(window, textvar=forPar)
forParBox.insert(0, "Enter loop parameters")
forParBox.place(x=254, y=139)
# for Button
b4 = Button(window, text="Create", relief=RIDGE, bg="#44ff4c", fg="Blue", command=for_create, font=("arial", 9, "bold"))
b4.place(x=382, y=136)
# range check box
rangeChkBut = Checkbutton(window, text="use range", onvalue=1, offvalue=0, variable=rangeChk)
rangeChkBut.place(x=442, y=138)
window.mainloop()
You should not use Tk() to create the dialog window. See Why are multiple instances of Tk discouraged?.
Use Toplevel() instead:
def var_create_fn():
window2 = Toplevel(window)
...
Update
Your program suggests that you are familiar with Python but may need help with Tkinter I suggest you look at Where to learn tkinter for Python?.
For python in general I suggest you search for Python exercises and try out a few until you find one that suits your level. I do, however, recommend Python 3 Module of the Week.

Resources