theard not responding while in mainloop - python-3.x

I'm working on a project where when a button is press in my controller a string needs to appear on the GUI. so I used threading, pyserial and tkinter for the mission but everytime I press the button in my controller it doesnt work after mainloop works, send text to the controller works, the terminal is a class I bulit with variable channel for serial
def chat_menu(terminal):
chat_window = Tk()
chat_window.geometry("650x480")
input_text = Text(chat_window, height=20, width=30)
output_text = Text(chat_window, height=20, width=30)
title = Label(chat_window, text="Chat Mode", font=("Arial",
14, "bold"))
title_in = Label(chat_window, text="Input", font=("Arial", 14,
"bold"))
title_out = Label(chat_window, text="Output", font=("Arial",
14, "bold"))
text = input_text.get("1.0", END)
submit_button = Button(chat_window, height=3, width=20,
text="Submit",
font=('Arial', 16, 'bold'),
command=lambda: send_text(terminal, chat_window, input_text))
back_button = Button(chat_window, height=3, width=20,
text='Back', font=('Arial', 16, 'bold'),
command=lambda:
terminal.close_main(chat_window, 'd'))
terminal.data = None
title.grid(row=0, column=1)
input_text.grid(row=1, column=0)
output_text.grid(row=1, column=2)
title_in.grid(row=2, column=0)
title_out.grid(row=2, column=2)
submit_button.grid(row=3, column=0)
back_button.grid(row=3, column=2)
thread = threading.Thread(target=receive_text(terminal,
output_text))
thread.start()
mainloop()
def receive_text(terminal, output):
time.sleep(2)
received = False
while True:
while terminal.channel.in_waiting > 0:
received_dataterminal.channel.read_until(expected='\n')
output.insert(END, received_data.decode("ascii"))
received = True
if received:
break

Related

Why is the tkinter text widget screwing up my cell sizes?

All was going well as seen in the 1st pic below. all the cells are the same perfect size. its great.
But then comes the implementation of the textbox. and all hell breaks loose. as seen in the 2nd picture it completely disrupts my grid layout. i dont want the textbox adjusting cell sizes, i want it to go where i tell it to go like all the other widgets do. Ive spent hours on this and no avail!
import tkinter as tk
from tkinter import ttk, scrolledtext
root = tk.Tk()
root.state('zoomed')
root.configure(background='#8585ad')
for i in range(0,20):
for x in range(0,20):
root.columnconfigure(i, weight=1)
root.rowconfigure(x, weight=1)
for i in range(0, 20): # 0-19(20 is excluded) so this will loop 10x
for x in range(0, 20):
tk.Label(root, text=f"C-{i}, R-{x}", bg="green", fg="white").grid(column=i, row=x, sticky="NSEW", padx=1, pady=1)
main_frame = tk.Label(root, text="MAIN FRAME", bg="blue", fg="white", anchor="n").grid(column=1, row=1, columnspan=18, rowspan=18, sticky="NSEW")
frame1 = tk.Label(root, text="FRAME 1", bg="red", fg="white", anchor="n").grid(column=2, row=2, columnspan=3, rowspan=16, sticky="NSEW")
frame2 = tk.Label(root, text="FRAME 2", bg="green", fg="white", anchor="n").grid(column=6, row=2, columnspan=6, rowspan=16, sticky="NSEW")
frame3 = tk.Label(root, text=" FRAME 3", bg="red", fg="white", anchor="n").grid(column=13, row=2, columnspan=5, rowspan=16, sticky="NSEW")
for i in range(2, 5): # start at 2 and end after the 3rd loop.
for x in range(3, 18): # to loop 15x and for index to start at 3 so i then put (3,18), 18-3 = 15
tk.Label(root, text=f"Button-{(x-2)}", bg="white", fg="black").grid(column=i, row=x, sticky="EW", padx=5, pady=5)
frame1_header = tk.Label(root, text="User Panel", bg="black", fg="white").grid(column=2, row=2, columnspan=3, sticky="SEW", padx=5, pady=5)
frame2_header = tk.Label(root, text="Editor", bg="black", fg="white").grid(column=6, row=2, columnspan=6, sticky="SEW", padx=5, pady=5)
frame3_header = tk.Label(root, text="Info Panel", bg="black", fg="white").grid(column=13, row=2, columnspan=5, sticky="SEW", padx=5, pady=5)
frame2_text_area = tk.Label(root, text="Text Box", bg="black", fg="white", anchor="center").grid(column=6, row=3, columnspan=4, rowspan=15, sticky="NSEW", padx=5, pady=5)
frame2_list_box = tk.Label(root, text="List Box", bg="grey", fg="white", anchor="center").grid(column=10, row=3, columnspan=2, rowspan=15, sticky="NSEW", padx=5, pady=5)
frame3_tab_panel = ttk.Notebook(root)
frame3_tab_panel.grid(column=13, row=3, columnspan=5, rowspan=15, sticky="NSEW", padx=5, pady=5)
tab1 = ttk.Frame(root)
tab2 = ttk.Frame(root)
tab3 = ttk.Frame(root)
frame3_tab_panel.add(tab1, text ='Generic Editor')
frame3_tab_panel.add(tab2, text ='Text Compare')
frame3_tab_panel.add(tab3, text ='Script Ref')
# width and height does indeed adjust the texbox size but the textbox still isnt properly sticking to the grid that i set.
frame3_tab_panel_tab1 = tk.Text(root, relief="ridge", bd=2, undo=True, wrap="none", background='#1E1E1E', insertbackground='white')#, width=40, height=10)
frame3_tab_panel_tab1.grid(column=13, row=4, columnspan=5, rowspan=14, padx=5, pady=5)
frame3_tab_panel_tab1.config(font=('Consolas bold',10), fg="white")
frame3_tab_panel_tab1.focus()
root.mainloop()
"""
text_area = scrolledtext.ScrolledText(tab1, wrap = tk.WORD, width=40, height=10, font=("Times New Roman", 15))
text_area.grid(column = 0, pady = 10, padx = 10)
text_area.focus()
"""
without textbox. as you can see its all perfectly even.
FYI: this is just a template im working on so i can better understand tk's positioning.
textbox ruining grid by not adjusting itself accordingly and fitting to the grid i set.
There is a lot of wrong doing in your code and you really should take a good tutorial for tkinter and you may wish to have a brief overview of tkinters geometry management.
The biggest issue is whats causes your code to work differently as you expect it, you always define the root as the master. Every widget, except for the root window, has a master and is set by the ONLY positional argument every widget requiers. Note that if None is given, the root window is set by default. This is, because tkinter is built hirachically and at the top of this hirachy stands the root window (the instance of tk.Tk()).
A master should be a container and this means either the root window, a Toplevel or a Frame. Masters can have so called children, which can be every other widget plus frames that are handled as children. The relationship between a master and a frame are various, but for the scope of this question we will just look at the geometry.
Every widget has a geometry and can be received by the universal widget method .winfo_geometry() that will give you a geometry string 'widthxheight±x_offset±y_offset' (e.g. '120x50-0+20'). The geometry string is the basement for every calculations to order your widgets, which you can affect by choosing a geometry manager and different optional keywords. With those information an output will be created and displayed on your screen.
Suggestion:
import tkinter as tk
from tkinter import ttk, scrolledtext
def populate_frame_1():
frame_1_label = tk.Label(frame_1,text='User Panel',
background = 'black',
foreground = 'white')
frame_1_label.grid(column=0,row=0,sticky='ew',columnspan=3)
frame_1.columnconfigure(0,weight=1)
frame_1.columnconfigure(1,weight=1)
frame_1.columnconfigure(2,weight=1)
for i in range(0, 3):
for x in range(1, 16):
l = tk.Button(frame_1, text=f"Button-{(x-2)}",
bg="white", fg="black")
l.grid(column=i, row=x, sticky="EW", padx=5, pady=5)
def populate_frame_2():
frame_2_label = tk.Label(frame_2,text='Editor',
background = 'black',
foreground = 'white')
textbox = tk.Text(frame_2,width=35)
listbox = tk.Listbox(frame_2,bg='yellow')
frame_2_label.grid(column=0,row=0,sticky='ew',columnspan=6)
textbox.grid(column=0,row=1,sticky='ns',columnspan=4)
listbox.grid(column=4,row=1,sticky='ns',columnspan=2)
frame_2.rowconfigure(1,weight=2)
def populate_frame_3():
frame_3_label = tk.Label(frame_3,text='Info Panel',
background = 'black',
foreground = 'white')
frame_3_label.grid(column=0,row=0,sticky='ew',columnspan=5)
control_panel = ttk.Notebook(frame_3)
tab1 = ttk.Frame(control_panel)
tab2 = ttk.Frame(control_panel)
tab3 = ttk.Frame(control_panel)
control_panel.add(tab1, text ='Generic Editor')
control_panel.add(tab2, text ='Text Compare')
control_panel.add(tab3, text ='Script Ref')
control_panel.grid(column=0,row=1,sticky='nswe')
frame3_tab_panel_tab1 = tk.Text(tab1, relief="ridge", bd=2, undo=True,
wrap="none", background='#1E1E1E',
insertbackground='white',width=40, height=10)
frame3_tab_panel_tab1.pack(fill=tk.BOTH,expand=True)
frame3_tab_panel_tab1.config(font=('Consolas bold',10), fg="white")
frame3_tab_panel_tab1.focus()
frame_3.rowconfigure(1,weight=2)
frame_3.columnconfigure(0,weight=2)
XOFFSET = 75
YOFFSET = 50
root = tk.Tk()
root.state('zoomed')
root.configure(background='#8585ad')
main_frame = tk.Frame(root,background='blue')
frame_1 = tk.Frame(main_frame,background='red')
frame_2 = tk.Frame(main_frame,background='green')
frame_3 = tk.Frame(main_frame,background='red')
main_frame.pack(fill=tk.BOTH,expand=True,
padx=XOFFSET,pady=YOFFSET)
frame_1.pack(side=tk.LEFT,fill=tk.BOTH,padx=XOFFSET,pady=YOFFSET,expand=True)
frame_2.pack(side=tk.LEFT,fill=tk.Y,pady=YOFFSET,expand=True)
frame_3.pack(side=tk.LEFT,fill=tk.BOTH,padx=XOFFSET,pady=YOFFSET,expand=True)
populate_frame_1()
populate_frame_2()
populate_frame_3()
root.mainloop()
Change
frame3_tab_panel_tab1.grid(
column=13, row=4, columnspan=5, rowspan=14, padx=5, pady=5
)
to
frame3_tab_panel_tab1.grid(
column=13, row=4, columnspan=5, rowspan=14, padx=5, pady=5,
sticky="NSEW"
)
I managed to solve it by replacing the Text() widget with the scrolledtext.ScrolledText() widget. Its strange. No grid was required and if i remove height and width then it messes it up. Why does height and width have such an impact? why does it even exist when you have things like column and row configure along with sticky. Tkinter is quite confusing sometimes with its logic. But anyways, got there in the end.
Here's the code in case anyone encounters a similar issue.
import tkinter as tk
from tkinter import ttk, scrolledtext
root = tk.Tk()
root.state('zoomed')
root.configure(background='#8585ad')
for i in range(0,20):
for x in range(0,20):
root.columnconfigure(i, weight=1)
root.rowconfigure(x, weight=1)
for i in range(0, 20): # 0-19(20 is excluded) so this will loop 10x
for x in range(0, 20):
tk.Label(root, text=f"C-{i}, R-{x}", bg="green", fg="white").grid(column=i, row=x, sticky="NSEW", padx=1, pady=1)
main_frame = tk.Label(root, text="MAIN FRAME", bg="blue", fg="white", anchor="n").grid(column=1, row=1, columnspan=18, rowspan=18, sticky="NSEW")
frame1 = tk.Label(root, text="FRAME 1", bg="red", fg="white", anchor="n").grid(column=2, row=2, columnspan=3, rowspan=16, sticky="NSEW")
frame2 = tk.Label(root, text="FRAME 2", bg="green", fg="white", anchor="n").grid(column=6, row=2, columnspan=6, rowspan=16, sticky="NSEW")
frame3 = tk.Label(root, text=" FRAME 3", bg="red", fg="white", anchor="n").grid(column=13, row=2, columnspan=5, rowspan=16, sticky="NSEW")
for i in range(2, 5): # start at 2 and end after the 3rd loop.
for x in range(3, 18): # to loop 15x and for index to start at 3 so i then put (3,18), 18-3 = 15
tk.Label(root, text=f"Button-{(x-2)}", bg="white", fg="black").grid(column=i, row=x, sticky="EW", padx=5, pady=5)
frame1_header = tk.Label(root, text="User Panel", bg="black", fg="white").grid(column=2, row=2, columnspan=3, sticky="SEW", padx=5, pady=5)
frame2_header = tk.Label(root, text="Editor", bg="black", fg="white").grid(column=6, row=2, columnspan=6, sticky="SEW", padx=5, pady=5)
frame3_header = tk.Label(root, text="Info Panel", bg="black", fg="white").grid(column=13, row=2, columnspan=5, sticky="SEW", padx=5, pady=5)
frame2_text_area = tk.Label(root, text="Text Box", bg="black", fg="white", anchor="center").grid(column=6, row=3, columnspan=4, rowspan=15, sticky="NSEW", padx=5, pady=5)
frame2_list_box = tk.Label(root, text="List Box", bg="grey", fg="white", anchor="center").grid(column=10, row=3, columnspan=2, rowspan=15, sticky="NSEW", padx=5, pady=5)
frame3_tab_panel = ttk.Notebook(root)
frame3_tab_panel.grid(column=13, row=3, columnspan=5, rowspan=15, sticky="NSEW", padx=5, pady=5)
frame3_tab_panel_tab1 = scrolledtext.ScrolledText(root, bd=2, undo=True, wrap="none", width=40, height=10, font=("Times New Roman", 15), background='#1E1E1E', insertbackground='white')
frame3_tab_panel_tab1.config(font=('Consolas bold',10), fg="white")
frame3_tab_panel_tab1.focus()
tab2 = ttk.Frame(root)
tab3 = ttk.Frame(root)
frame3_tab_panel.add(frame3_tab_panel_tab1, text ='Generic Editor')
frame3_tab_panel.add(tab2, text ='Text Compare')
frame3_tab_panel.add(tab3, text ='Script Ref')
root.mainloop()

My code is giving an error, and I can't see why

Warning: This will be long (sorry)
I am using Tkinter in python, with PyCharm IDE. I am making a text-based rpg where you need to create an account to access settings which is all done and working. However, when you have previously made the account when logging in, if you then go back to main menu and try to login again right away it comes up with an error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Vandkb\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1885, in __call__
return self.func(*args)
File "C:\Users\Vandkb\PycharmProjects\VideoGame\main.py", line 8, in combined_func
f(*args, **kwargs)
File "C:\Users\Vandkb\PycharmProjects\VideoGame\main.py", line 161, in Login
Settings()
TypeError: 'Tk' object is not callable
As far as I have been able to find, there is no reason why it shouldn't work. My code is as follows (it is long)
from tkinter import *
import json
import os
def combine_funcs(*funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func
#Title Screen
def TitleScreen():
global TitleScreen
TitleScreen = Tk()
TitleScreen.geometry("980x470")
TitleScreen.resizable(False, False)
TitleScreen.title("Breaking the System - Main Menu")
Title1 = Label(TitleScreen, text="Breaking", font=("Arial", 50, "underline"))
Space1 = Label(TitleScreen, text=" ", font=("Arial", 50))
Title2 = Label(TitleScreen, text="the", font=("Arial", 50, "underline"))
Space2 = Label(TitleScreen, text=" ", font=("Arial", 50))
Title3 = Label(TitleScreen, text="System", font=("Arial", 50, "underline"))
Start = Button(TitleScreen, text="Start", font=("Arial", 20))
Settings = Button(TitleScreen, text="Settings", font=("Arial", 20),
command=combine_funcs(SettingsLogin, TitleScreen.withdraw))
Exit = Button(TitleScreen, text="Exit", font=("Arial", 20), command=Close)
Developer =Label(TitleScreen, text="Developer: Kailan Van der Putten", font=("Arial", 10))
Title1.grid(row=0, column=0)
Space1.grid(row=1, column=1)
Title2.grid(row=2, column=2)
Space2.grid(row=3, column=3)
Title3.grid(row=4, column=4)
Start.grid(row=5, column=0)
Settings.grid(row=5, column=2)
Exit.grid(row=5, column=4)
Developer.grid(row=0, column=4, sticky=NE)
#Account Creation
def AccountCreation():
global AccountCreation
AccountCreation = Tk()
AccountCreation.geometry("980x470")
AccountCreation.resizable(False, False)
AccountCreation.title("Breaking the System - Create an account")
global created_username
global created_password
AccountCreationRequest = Label(AccountCreation, text="Please create an account to access!",
font=("Arial", 20))
Space1 = Label(AccountCreation, text=" ", font=("Arial", 20))
Username = Label(AccountCreation, text="Username:", font=("Arial", 15))
created_username = Entry(AccountCreation, font=("Arial", 20))
Password = Label(AccountCreation, text="Password:", font=("Arial", 15))
created_password = Entry(AccountCreation, font=("Arial", 20))
Create = Button(AccountCreation, text="Create", font=("Arial", 15),
command=combine_funcs(Acceptable, AccountCreation.withdraw))
Back = Button(AccountCreation, text="Back", font=("Arial", 15),
comman=combine_funcs(TitleScreen.deiconify, AccountCreation.withdraw))
Sword1 = Label(AccountCreation, text=" /", font=("Arial", 20))
Sword2 = Label(AccountCreation, text="O===[====================-", font=("Arial", 20))
Sword3 = Label(AccountCreation, text=" " + '\\', font=("Arial", 20))
AccountCreationRequest.grid(row=0, column=0)
Space1.grid(row=1, column=0)
Username.grid(row=2, column=0, sticky=W)
created_username.grid(row=3, column=0, sticky=W)
Password.grid(row=4, column=0, sticky=W)
created_password.grid(row=5, column=0, sticky=W)
Create.grid(row=6, column=0, sticky=W)
Back.grid(row=6, column=0)
Sword1.grid(row=3, column=1, sticky=SW)
Sword2.grid(row=4, column=1, sticky=W)
Sword3.grid(row=5, column=1, sticky=NW)
#Settings (Login)
def SettingsLogin():
global SettingsLogin
SettingsLogin = Tk()
SettingsLogin.geometry("980x470")
SettingsLogin.resizable(False, False)
SettingsLogin.title("Breaking the System - Login")
global entered_username
global entered_password
Login1 = Label(SettingsLogin, text="Login", font=("Arial", 20))
Username = Label(SettingsLogin, text="Username:", font=("Arial", 15))
entered_username = Entry(SettingsLogin, font=("Arial", 20))
Password = Label(SettingsLogin, text="Password:", font=("Arial", 15))
entered_password = Entry(SettingsLogin, font=("Arial", 20))
LoginButton = Button(SettingsLogin, text="Login", font=("Arial", 15),
command=combine_funcs(Login, SettingsLogin.withdraw))
Back = Button(SettingsLogin, text="Back", font=("Arial", 15),
command=combine_funcs(TitleScreen.deiconify, SettingsLogin.withdraw))
DeleteAccount = Button(SettingsLogin, text="Delete Account", font=("Arial", 15),
command=combine_funcs(Delete))
CreateAccount = Button(SettingsLogin, text="Create Account", font=("Arial", 15),
command=combine_funcs(AccountCreation, SettingsLogin.withdraw))
Space1 = Label(SettingsLogin, text=" ", font=("Arial", 20))
Space2 = Label(SettingsLogin, text=" ", font=("Arial", 20))
HP1 = Label(SettingsLogin, text=" _________", font=("Arial", 20))
HP2 = Label(SettingsLogin, text=" {_________}", font=("Arial", 20))
HP3 = Label(SettingsLogin, text=" )=======(", font=("Arial", 20))
HP4 = Label(SettingsLogin, text=" / \\", font=("Arial", 20))
HP5 = Label(SettingsLogin, text="| _________ |", font=("Arial", 20))
HP6 = Label(SettingsLogin, text="|| ||", font=("Arial", 20))
HP7 = Label(SettingsLogin, text="|| ||", font=("Arial", 20))
HP8 = Label(SettingsLogin, text="|| ||", font=("Arial", 20))
HP9 = Label(SettingsLogin, text="|| ||", font=("Arial", 20))
HP10 = Label(SettingsLogin, text="|\'----------------\'|", font=("Arial", 20))
HP11 = Label(SettingsLogin, text="`-.................-\'", font=("Arial", 20))
Space1.grid(row=0, column=0)
HP1.grid(row=0, column=1)
HP2.grid(row=1, column=1)
HP3.grid(row=2, column=1)
HP4.grid(row=3, column=1)
HP5.grid(row=4, column=1)
HP6.grid(row=5, column=1)
HP7.grid(row=6, column=1)
HP8.grid(row=7, column=1)
HP9.grid(row=8, column=1)
HP10.grid(row=9, column=1)
HP11.grid(row=10, column=1)
Space2.grid(row=0, column=2)
Login1.grid(row=1, column=3)
Username.grid(row=2, column=3)
entered_username.grid(row=3, column=3)
Password.grid(row=4, column=3)
entered_password.grid(row=5, column=3)
CreateAccount.grid(row=6, column=3)
DeleteAccount.grid(row=7, column=3)
LoginButton.grid(row=8, column=3)
Back.grid(row=9, column=3)
#Login
def Login():
global username2
global password2
username2 = str(entered_username.get())
password2 = str(entered_password.get())
with open("UserInfo.json", "r") as read_file:
userword = json.load(read_file)
if userword["Username"] == username2 and userword["Password"] == password2:
Settings()
else:
Unmatched()
read_file.close()
#Unmatched
def Unmatched():
global Unmatched
Unmatched = Tk()
Unmatched.geometry("388x160")
Unmatched.resizable(False, False)
Unmatched.title("Breaking the System")
Incorrect1 = Label(Unmatched, text="Username and Password are not incorrect.", font=("Arial", 15))
Space = Label(Unmatched, text=" ", font=("Arial", 15))
Done = Button(Unmatched, text="Done", font=("Arial", 15),
command=combine_funcs(SettingsLogin.deiconify, Unmatched.destroy))
Incorrect1.grid(row=0, column=0)
Space.grid(row=2, column=0)
Done.grid(row=3, column=0)
#Delete
def Delete():
global username2
global password2
username2 = str(entered_username.get())
password2 = str(entered_password.get())
with open("UserInfo.json", "r") as read_file:
userword = json.load(read_file)
if userword["Username"] == username2 and userword["Password"] == password2:
os.remove("UserInfo.json")
TitleScreen.deiconify()
SettingsLogin.withdraw()
else:
Unmatched()
read_file.close()
#Settings
def Settings():
global Settings
Settings = Tk()
Settings.geometry("980x470")
Settings.resizable(False, False)
Settings.title("Breaking the System - Settings")
Violence = Label(Settings, text="Level of Violence", font=("Arial", 20))
Back = Button(Settings, text="Back", font=("Arial", 20), command=combine_funcs(TitleScreen.deiconify, Settings.withdraw))
Violence.grid(row=1, column=0)
Back.grid(row=2, column=0)
#Pause Screen
#Save Screen
#Inventory
#Info about person speaking
#The Game
#User Information
def UserInfo():
List = {"Username": created_username.get(), "Password": created_password.get()}
with open("UserInfo.json", "w") as write_file:
json.dump(List, write_file)
write_file.close()
#Acceptable
def Acceptable():
global username1
global password1
username1 = str(created_username.get())
password1 = str(created_password.get())
if username1 == "" and password1 == "":
Blank()
elif username1.isspace() and password1.isspace():
BothFalseWhite()
elif not username1.isalnum() and not password1.isalnum() and not username1.isspace() and not password1.isspace():
BothFalseSpChar()
elif not username1.isalnum() or username1.isspace() or not password1.isalnum() or password1.isspace() or username1 == "" or password1 == "":
BothFalse()
else:
SettingsLogin.deiconify()
UserInfo()
#Blank
def Blank():
global Blank
Blank = Tk()
Blank.geometry("388x160")
Blank.resizable(False, False)
Blank.title("Breaking the System")
Incorrect1 = Label(Blank, text="Username and Password are not accepted,", font=("Arial", 15))
Incorrect2 = Label(Blank, text="make sure to input letters or numbers.", font=("Arial", 15))
Space = Label(Blank, text=" ", font=("Arial", 15))
Done = Button(Blank, text="Done", font=("Arial", 15),
command=combine_funcs(AccountCreation.deiconify, Blank.destroy))
Incorrect1.grid(row=0, column=0)
Incorrect2.grid(row=1, column=0)
Space.grid(row=2, column=0)
Done.grid(row=3, column=0)
#Both False - Special Characters
def BothFalseSpChar():
global BothFalseSpChar
BothFalseSpChar = Tk()
BothFalseSpChar.geometry("388x160")
BothFalseSpChar.resizable(False, False)
BothFalseSpChar.title("Breaking the System")
Incorrect1 = Label(BothFalseSpChar, text="Username and Password are not accepted,", font=("Arial", 15))
Incorrect2 = Label(BothFalseSpChar, text="make sure to input letters or numbers.", font=("Arial", 15))
Space = Label(BothFalseSpChar, text=" ", font=("Arial", 15))
Done = Button(BothFalseSpChar, text="Done", font=("Arial", 15),
command=combine_funcs(AccountCreation.deiconify, BothFalseSpChar.destroy))
Incorrect1.grid(row=0, column=0)
Incorrect2.grid(row=1, column=0)
Space.grid(row=2, column=0)
Done.grid(row=3, column=0)
#Both False - Only Whitespaces
def BothFalseWhite():
global BothFalseWhite
BothFalseWhite = Tk()
BothFalseWhite.geometry("388x160")
BothFalseWhite.resizable(False, False)
BothFalseWhite.title("Breaking the System")
Incorrect1 = Label(BothFalseWhite, text="Username and Password are not accepted,", font=("Arial", 15))
Incorrect2 = Label(BothFalseWhite, text="make sure to input letters or numbers.", font=("Arial", 15))
Space = Label(BothFalseWhite, text=" ", font=("Arial", 15))
Done = Button(BothFalseWhite, text="Done", font=("Arial", 15),
command=combine_funcs(AccountCreation.deiconify, BothFalseWhite.destroy))
Incorrect1.grid(row=0, column=0)
Incorrect2.grid(row=1, column=0)
Space.grid(row=2, column=0)
Done.grid(row=3, column=0)
#Both False - One or both reasons
def BothFalse():
global BothFalse
BothFalse = Tk()
BothFalse.geometry("388x160")
BothFalse.resizable(False, False)
BothFalse.title("Breaking the System")
Incorrect1 = Label(BothFalse, text="Username and Password are not accepted,", font=("Arial", 15))
Incorrect2 = Label(BothFalse, text="make sure to input letters or numbers.", font=("Arial", 15))
Space = Label(BothFalse, text=" ", font=("Arial", 15))
Done = Button(BothFalse, text="Done", font=("Arial", 15),
command=combine_funcs(AccountCreation.deiconify, BothFalse.destroy))
Incorrect1.grid(row=0, column=0)
Incorrect2.grid(row=1, column=0)
Space.grid(row=2, column=0)
Done.grid(row=3, column=0)
#Exit Function
def Close():
TitleScreen.quit()
#Other Stuff
TitleScreen()
TitleScreen.mainloop()
Again I am very sorry the code is so long, I hope you can help.
Thanks.

I would like to use a buttons output in tkinter to answer an input in another function

This is a simple memory game, where the voice says a number, and you have to click the button with the same number. I want to use it with comparing lists. If you guessed correctly one the code will add another, and another and so on. My problem is, that I have the buttons and with the function button click I can define the values with print. I have the code where it should be linked, but I cannot lined them together. Please help me :)
import pyttsx3
import time
import random
import tkinter as tk
from tkinter import *
root = Tk()
root.title("A little memory game")
sound_or_color = IntVar() # for radiobutton 1, sound, 2 color
quiz_list = [] # this will be the random number
your_list = [] # this will get the input form the buttons
guess = StringVar() # for the label to add guesses
best_score = 2
best_score_final = IntVar()
best_score_final.set(best_score)
actual_score_actual = IntVar()
def button_click(number):
your_list.append(number)
print(your_list)
def game():
# if sound_or_color == 1: # this will work with sound
actual_score = 0
global best_score
while True:
# this will generate the task, each round
quiz_number = random.randint(1, 9)
quiz_list.append(quiz_number)
speaker = pyttsx3.init()
speaker.say(quiz_list)
speaker.runAndWait()
print(quiz_list)
guess.set("click your guess(es)")
**# take the user's guess:
for i in range(0, len(quiz_list)):
# your_list.append(int(input())) <------the problematic part
button_click()**
# was the guess right?
if quiz_list == your_list:
actual_score += 1
actual_score_actual.set(actual_score)
your_list.clear()
else:
end_text = "Coungratulation, your score is", actual_score
your_list.clear()
quiz_list.clear()
speaker2 = pyttsx3.init()
speaker2.say(end_text)
speaker2.say("Click the start button, to play again")
speaker2.runAndWait()
if actual_score > best_score:
best_score = actual_score
best_score_final.set(best_score)
break
# labels:
label_best = tk.Label(root, text="best score: ",
textvariable=best_score_final, fg="#900C3F")
label_score = tk.Label(root, text="actual score: ",
textvariable=actual_score_actual, fg="#07A0F1")
label_best2 = tk.Label(root, text="best score: ", fg="#900C3F")
label_score2 = tk.Label(root, text="actual score: ", fg="#07A0F1")
label_input = tk.Label(root, textvariable=guess)
# define buttons:
button_start = Button(root, text="Start",
command=game, bg="#65B9E5")
button_0 = Radiobutton(root, text="with sound",
variable=sound_or_color, value=1)
button_10 = Radiobutton(root, text="with color",
variable=sound_or_color, value=2)
button_1 = Button(root, text="1", padx=40, pady=20,
command=lambda: button_click(1))
button_2 = Button(root, text="2", padx=40, pady=20,
command=lambda: button_click(2))
button_3 = Button(root, text="3", padx=40, pady=20,
command=lambda: button_click(3))
button_4 = Button(root, text="4", padx=40, pady=20,
command=lambda: button_click(4))
button_5 = Button(root, text="5", padx=40, pady=20,
command=lambda: button_click(5))
button_6 = Button(root, text="6", padx=40, pady=20,
command=lambda: button_click(6))
button_7 = Button(root, text="7", padx=40, pady=20,
command=lambda: button_click(7))
button_8 = Button(root, text="8", padx=40, pady=20,
command=lambda: button_click(8))
button_9 = Button(root, text="9", padx=40, pady=20,
command=lambda: button_click(9))
# Put buttons on the screen
label_input.grid(row=0, column=0, columnspan=3)
button_1.grid(row=1, column=0)
button_2.grid(row=1, column=1)
button_3.grid(row=1, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=3, column=0)
button_8.grid(row=3, column=1)
button_9.grid(row=3, column=2)
button_0.grid(row=4, column=0)
button_10.grid(row=4, column=1)
button_start.grid(row=4, column=2)
label_score2.grid(row=5, column=0)
label_best2.grid(row=5, column=1)
label_score.grid(row=6, column=0)
label_best.grid(row=6, column=1)
root.mainloop()

SQLite Python Query not working when using tkinter with no error messages

I am learning python for my A level and have come across a problem in my project, any help would be immensely appreciated. Thank you.
I have a series of tkinter pages that are designed to be linked by one central page. The search, delete and update functions successfully run SQL queries on their own but lose their functionality when called from the main page, I am getting no visible error messages. I am running SQLite 3.11.2 and Python 3.7.3
The main page calls the attendance page like this (triggered using a button):
def ap():
AttendancePage.Attendance(Tk())
The actual attendance page is as follows:
import tkinter as tk
from tkinter import*
import tkinter.messagebox
import NEA_SQL_IIII
class Attendance:
def __init__ (self,root):
self.root =root
self.root.title("ODIN Attendance Page")
self.root.geometry("1350x750+0+0")
self.root.config(bg="ghost white")
#These are all the entry widgets, where the values will be added
Absent = BooleanVar()
AbsenceNote = BooleanVar()
TotalAbsences = IntVar()
StudentName = StringVar()
StudentID = StringVar()
should_auto = BooleanVar()
#function
#This is the section that will give the buttons their functionality
def Clear():
self.entStudentID.delete(0,END)
self.entStudentName.delete(0,END)
self.chkAbsent.deselect()
self.chkAbsenceNote.deselect()
self.entTotalAbsences.delete(0,END)
def Exit():
Exit = tk.messagebox.askyesno("ODIN","Do you wish to exit?")
if Exit > 0:
root.destroy()
return
def searchDatabase():
attendanceList.delete(0,END)
for row in NEA_SQL_IIII.searchA(StudentID.get(),StudentName.get()):
attendanceList.insert(END,row,str(""))
def viewData():
attendanceList.delete(0,END)
for row in NEA_SQL_IIII.displayA():
attendanceList.insert(END,row,str(""))
def deleteData():
if(len(StudentName.get())!=0):
NEA_SQL_IIII.DeleteDataA(sd[0])
Clear()
viewData()
def AttendRec(event):
global sd
searchAttend = attendanceList.curselection()[0]
sd = attendanceList.get(searchAttend)
self.entStudentID.delete(0,END)
self.entStudentID.insert(END,sd[0])
self.entStudentName.delete(0,END)
self.entStudentName.insert(END,sd[1])
self.chkAbsent.deselect()
self.chkAbsent.select()
self.chkAbsenceNote.deselect()
self.chkAbsenceNote.select()
self.entTotalAbsences.delete(0,END)
self.entTotalAbsences.insert(END,sd[4])
def Update():
if(len(StudentID.get())!=0):
NEA_SQL_IIII.DeleteDataA(sd[0])
if(len(StudentID.get())!=0):
NEA_SQL_IIII.addStudentA(StudentID.get(),StudentName.get(),Absent.get(),AbsenceNote.get(),TotalAbsences.get())
attendanceList.delete(0,END)
attendanceList.insert(END,(StudentID.get(),StudentName.get(),Absent.get(),AbsenceNote.get(),TotalAbsences.get()))
#Frames
#These will define all the different frames
MainFrame = Frame(self.root, bg="Ghost White")
MainFrame.grid()
TitFrame = Frame(MainFrame, bd=2, padx=54, pady=8, bg="Ghost White", relief = RIDGE)
TitFrame.pack(side=TOP)
self.lblTit = Label(TitFrame ,font=('ariel', 47,'bold'),text="ODIN Attendance Page",bg="Ghost White")
self.lblTit.grid()
ButtonFrame = Frame(MainFrame, bd=2, width=1350, height=70, padx=18, pady=10, bg="blue2", relief = RIDGE)
ButtonFrame.pack(side=BOTTOM)
DataFrame = Frame(MainFrame, bd=1, width=1300, height=400, padx=20, pady=20, bg="ghost white", relief = RIDGE)
DataFrame.pack(side=BOTTOM)
#DataFrameTOP = LabelFrame(DataFrame, bd=1, width=1000, height=300, padx=20, pady=4, relief = RIDGE, bg="Ghost White", font=('ariel', 20,'bold'), text = "Student Info\n")
#DataFrameTOP.pack(side=TOP)
DataFrameLEFT = LabelFrame(DataFrame, bd=1, width=450, height=200, padx=20,pady=3, bg="Ghost White", relief = RIDGE, font=('ariel', 20,'bold'), text = "Student Info\n")
DataFrameLEFT.pack(side=LEFT)
DataFrameRIGHT = LabelFrame(DataFrame, bd=1, width=450, height=200, padx=31,pady=3, bg="Ghost White", relief = RIDGE, font=('ariel', 20,'bold'), text = "Student Details\n")
DataFrameRIGHT.pack(side=RIGHT)
#Label and Entry Widget
#These are the widgets that will allow for labels onto the entry sections
self.lblStudentID = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Student ID", padx=2, pady=2, bg="Ghost White")
self.lblStudentID.grid(row=0, column=0, sticky=W)
self.entStudentID = Entry(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=StudentID, width=39)
self.entStudentID.grid(row=0, column=1)
self.lblStudentName = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Student Name", padx=2, pady=2, bg="Ghost White")
self.lblStudentName.grid(row=1, column=0, sticky=W)
self.entStudentName = Entry(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=StudentName, width=39)
self.entStudentName.grid(row=1, column=1)
self.lblAbsent = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Absent?", padx=2, pady=2, bg="Ghost White")
self.lblAbsent.grid(row=2, column=0, sticky=W)
self.chkAbsent = Checkbutton(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=Absent, variable = should_auto, onvalue = True, offvalue = False, width=39)
self.chkAbsent.grid(row=2, column=1)
self.lblAbsenceNote = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Absence Note?", padx=2, pady=2, bg="Ghost White")
self.lblAbsenceNote.grid(row=3, column=0, sticky=W)
self.chkAbsenceNote = Checkbutton(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=AbsenceNote, width=39, onvalue = True, offvalue = False)
self.chkAbsenceNote.grid(row=3, column=1)
self.lblTotalAbsences = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Total Absences?", padx=2, pady=2, bg="Ghost White")
self.lblTotalAbsences.grid(row=4, column=0, sticky=W)
self.entTotalAbsences = Entry(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=TotalAbsences, width=39)
self.entTotalAbsences.grid(row=4, column=1)
#scrollbar
scrollbar = Scrollbar(DataFrameRIGHT)
scrollbar.grid(row=0, column=1, sticky = 'ns')
attendanceList = Listbox(DataFrameRIGHT, width=41, height=16, font=('ariel',12,'bold'), yscrollcommand=scrollbar.set)
attendanceList.bind('<<ListboxSelect>>',AttendRec)
attendanceList.grid(row=0, column=0, padx=8)
scrollbar.config(command = attendanceList.yview)
#button
#self.btnAddDate = Button(ButtonFrame, text='Add New', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=addData)
#self.btnAddDate.grid(row=0, column=0)
self.btnDisplay = Button(ButtonFrame, text='Display', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=viewData)
self.btnDisplay.grid(row=0, column=0)
self.btnClear = Button(ButtonFrame, text='Clear', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=Clear)
self.btnClear.grid(row=0, column=1)
self.btnDelete = Button(ButtonFrame, text='Delete', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = deleteData)
self.btnDelete.grid(row=0, column=2)
self.btnSearch = Button(ButtonFrame, text='Search', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = searchDatabase)
self.btnSearch.grid(row=0, column=3)
#self.btnUpdate = Button(ButtonFrame, text='Update', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = updateData)
#self.btnUpdate.grid(row=0, column=4)
self.btnUpdate = Button(ButtonFrame, text='Update', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = Update)
self.btnUpdate.grid(row=0, column=4)
self.btnQuit = Button(ButtonFrame, text='Quit', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=Exit)
self.btnQuit.grid(row=0, column=5)
if __name__=='__main__':
root = tk.Tk()
application = Attendance(root)
root.mainloop()'''
The SQL code that is being called is:
def Attendance():
con=sqlite3.connect("Attendance.db")
cur=con.cursor()
cur.execute("CREATE TABLE IF NOT EXIST Attendance (Absent BOOLEAN, AbsenceNote BOOLEAN, TotalAbsences INTEGER, FOREIGN KEY StudentName REFERENCES StudentRecord(StudentName),FOREIGN KEY StudentID REFERENCES StudentRecord(StudentID), PRIMARY KEY(StudentID)")
con.commit()
con.close()
def displayA():
con=sqlite3.connect("Attendance.db")
cur=con.cursor()
cur.execute("SELECT * FROM Attendance")
rows =cur.fetchall()
con.close()
return rows
def DeleteDataA(StudentID):
con=sqlite3.connect("Attendance.db")
cur=con.cursor()
cur.execute("DELETE FROM Attendance WHERE StudentID=?", (StudentID,))
con.commit()
return con, cur
con.close()
def searchA(StudentName="", StudentID=""):
con=sqlite3.connect("Attendance.db", isolation_level=None)
cur=con.cursor()
cur.execute("SELECT * FROM Attendance WHERE StudentName=? OR StudentID=?", (StudentName,StudentID,))
rows = cur.fetchall()
con.close()
return rows
def UpdateDataA(StudentID="", StudentName="", Behaviour="", Achievement="", Detention="", ProgressLevel=""):
con=sqlite3.connect("StudentRecord.db")
cur=con.cursor()
cur.execute("UPDATE StudentRecord SET StudentName=?, Behaviour=?, Achievement=?, Detention=?, ProgressLevel=? WHERE StudentID=? ", (StudentID,StudentName,Behaviour,Achievement,Detention,ProgressLevel))
con.commit()
con.close()

Updating or reseting a tkinter display

I'm working on a small Tkinter program where once started it prompts you to input a name then after clicking submit it will display "Welcome to my world". I'm having issues with either retrieving the input and displaying it in a new window or updating the window with the new information but it displays Py_Var1 as the entry name. What am I doing wrong, is it because I'm trying to display information in a new window or am I using the functions wrong?
Here is my code
from tkinter import *
root = Tk()
#Functions
def info():
a= entry_1.get()
def close_window(root):
root.destroy()
def comb(event=None):
info()
close_window(root)
#Display
input_1 = Label(root, text=" Name: ", bg= "light grey", fg="blue", font=("Arial", 16))
entry_1 = Entry(root, bg= "white", fg= "black", bd= 5, relief= SUNKEN, font=("Arial", 12))
button = Button(root, text="Submit", command=comb, bd= 6, relief= RAISED, fg='blue', font=("Arial", 12))
root.bind("<Return>", comb)
aVar = StringVar(entry_1.get())
aVar.set(aVar)
#entry display
input_1.grid(row=1, sticky=E)
entry_1.grid(row=1, column=1)
button.grid(row=3, column=1)
root.mainloop()
##Second Window
root = Tk()
Var = StringVar()
Var.set(info)
t1 = Label(root, text="Welcome")
t2 = Label(root, text= Var)
t3 = Label(root, text="to my world")
#Display
t1.grid(row=1, column=1)
t2.grid(row=1, column=2)
t3.grid(row=1, column=3)
root.mainloop()
I think the problem was that you were trying to access a variable which you assigned before you destroyed the window after it was destroyed which Tkinter can't do. Needed a global variable. Your code should work now.
from tkinter import *
root = Tk()
#Functions
def info():
global a
a= entry_1.get()
def close_window(root):
root.destroy()
def comb(event=None):
info()
close_window(root)
#Display
input_1 = Label(root, text=" Name: ", bg= "light grey", fg="blue", font=("Arial", 16))
entry_1 = Entry(root, bg= "white", fg= "black", bd= 5, relief= SUNKEN, font=("Arial", 12))
button = Button(root, text="Submit", command=comb, bd= 6, relief= RAISED, fg='blue', font=("Arial", 12))
root.bind("<Return>", comb)
#entry display
input_1.grid(row=1, sticky=E)
entry_1.grid(row=1, column=1)
button.grid(row=3, column=1)
root.mainloop()
##Second Window
root = Tk()
t1 = Label(root, text="Welcome "+str(a)+" to my world")
##t2 = Label(root, text= Var)
##t3 = Label(root, text="to my world") # cleaner this way
#Display
t1.grid(row=1, column=1)
#t2.grid(row=1, column=2)
#t3.grid(row=1, column=3)
root.mainloop()
It is not running because there are many errors and no logic.
You use many functions whithout reason and none of them returns values.
Also, you destroy the Entry widget closing the root window and after that
you are asking to get the text from the Entry you just destroyed using a function which don't return anything. Even if you don't destroy the root window and use a toplevel window, still this program will not work because your function don't return anything.
It looks like you don't understand the basic usage of functions. Consider to play with functions with simple programs before try something more complicated.

Resources