Having some trouble using geometry manager .grid in tkinter - python-3.x

I have some code here and I can't figure out why everything is getting smashed together. Also with the function I have, it isn't getting the actual text that I type into the Text widget. I'm a semi-newbie to Python and have been developing this game for a while.
def comments():
root = tk.Tk()
root.title("Comments")
root.geometry("300x200+300+300")
var = tk.IntVar()
top_frame = tk.Frame(root, bg="red", width=300, height=50)
name_label = tk.Label(top_frame, text="Username", bg='red', fg="yellow", font=("arial, 17"), justify=LEFT)
name_entry = tk.Entry(top_frame)
comment_frame = tk.Frame(root, bg="yellow", width=300, height=100, relief=GROOVE)
comment_entry = tk.Text(comment_frame, bd=2, relief=SUNKEN, width=35, height=5)
comment = comment_entry.get('1.0', 'end-1c')
def save_comment():
#if like_dislike == 0:
#dislikes =+ 1
#opinion = dislike
#elif like_dislike == 1:
#likes =+ 1
#opinion = like
now = datetime.datetime.now()
if now.hour > 12:
hour = now.hour-12
meridiem = 'pm'
else:
hour = now.hour
meridiem = 'am'
timestamp = str(now.month)+'/'+str(now.day)+'/'+str(now.year)+'\t'+str(hour)+':'+str(now.minute)+':'+str(now.second)
with open(comments_file, 'a') as file:
file.write(comment + timestamp + meridiem + '\r\n\n')
exit_comments = tk.messagebox.askyesno('Exit', 'Return to About Page?')
if exit_comments == True:
root.destroy()
like_dislike_frame = tk.Frame(root, relief=GROOVE, bg='green', width=300, height=50)
#like_button = tk.Button(like_dislike_frame, text="Like").grid(row=2, sticky=W, padx="6px")
#dislike_button = tk.Button(like_dislike_frame, text="Dislike").grid(row=2)
like_button = tk.Checkbutton(like_dislike_frame, text="Like", font=("arial, 12"), onvalue=1,offvalue=0, variable=var, bg='green', fg='yellow')
dislike_button = tk.Checkbutton(like_dislike_frame, text="Dislike", font=("arial, 12"), onvalue=1,offvalue=0, variable=var, bg='green', fg='yellow')
submit_button = tk.Button(like_dislike_frame, text="Submit", command=save_comment)
top_frame.grid(row=0, column=0, columnspan=3)
name_label.grid(row=0, sticky=W, padx="5px")
name_entry.grid(row=0, sticky=E, padx="5px")
comment_frame.grid(row=1, column=0, columnspan=3)
comment_entry.grid(row=1, column=0, sticky=E)
like_dislike_frame.grid(row=2, columnspan=2)
like_button.grid(row=2, sticky=W, padx="6px")
dislike_button.grid(row=2, padx="6px")
submit_button.grid(row=2, sticky=E)
root.mainloop()**

Basically you haven't specified unique row/column numbers for most of your widgets.
Each frame has its own row/grid system so you can place a frame at row=0 column=0. If that frame then has two widget inside it, one to the right of the other you'd use row=0 column=0, row=0 column=1 for each widget respectively.
I looked at the like/dislike frame and specified a column for each of those
like_button.grid(row=0,column=0, sticky=W, padx="6px")
dislike_button.grid(row=0,column=1, padx="6px")
submit_button.grid(row=0,column=2, sticky=E)
They now appear spaced out correctly.

Related

Filling Tkinter window

I'm having some trouble get my frames and widgets to fill out the tkinter window. I don't know what I have wrong here. I have been trying to mess around with columnspan sticky and width/height. I am fairly new to using Tkinter and still trying to figure out the basics of widgets and geometry management.
def comments():
root = tk.Tk()
root.title("Comments")
root.geometry("300x200+300+300")
var = tk.IntVar()
top_frame = tk.Frame(root, bg="red", width=350, height=50)
name_label = tk.Label(top_frame, text="Username", bg='red', fg="yellow", font=("arial, 17"))
name_entry = tk.Entry(top_frame)
comment_frame = tk.Frame(root, bg="yellow", width=40, height=70, bd="3px", relief=GROOVE)
comment_entry = tk.Text(comment_frame, bd=2, relief=SUNKEN, width=40, height=5)
comment = comment_entry.get('1.0', 'end-1c')
like_dislike_frame = tk.Frame(root, relief=GROOVE, bg='green', width=300, height=50)
#like_button = tk.Button(like_dislike_frame, text="Like").grid(row=2, sticky=W, padx="6px")
#dislike_button = tk.Button(like_dislike_frame, text="Dislike").grid(row=2)
like_button = tk.Checkbutton(like_dislike_frame, text="Like", font=("arial, 12"), onvalue=1,offvalue=0, variable=var, bg='green', fg='yellow')
dislike_button = tk.Checkbutton(like_dislike_frame, text="Dislike", font=("arial, 12"), onvalue=1,offvalue=0, variable=var, bg='green', fg='yellow')
def save_comment():
#if like_dislike == 0:
#dislikes =+ 1
#opinion = dislike
#elif like_dislike == 1:
#likes =+ 1
#opinion = like
now = datetime.datetime.now()
if now.hour > 12:
hour = now.hour-12
meridiem = 'pm'
else:
hour = now.hour
meridiem = 'am'
timestamp = str(now.month)+'/'+str(now.day)+'/'+str(now.year)+'\t'+str(hour)+':'+str(now.minute)+':'+str(now.second)
with open(comments_file, 'a') as file:
file.write(comment + timestamp + meridiem + '\r\n\n')
exit_comments = tk.messagebox.askyesno('Exit', 'Return to About Page?')
if exit_comments == True:
root.destroy()
submit_button = tk.Button(like_dislike_frame, text="Submit", command=save_comment)
top_frame.grid(row=0, column=0, sticky=EW)
name_label.grid(row=0, column=0, sticky=W, padx="5px")
name_entry.grid(row=0, column=1, sticky=E, padx="5px")
comment_frame.grid(row=1, column=0)
comment_entry.grid(row=1, column=0, sticky=EW)
like_dislike_frame.grid(row=2, column=0, sticky=NSEW)
like_button.grid(row=2, column=0, sticky=W, padx="6px")
dislike_button.grid(row=2, column=1, padx="6px")
submit_button.grid(row=2, column=2, sticky=E)
root.mainloop()

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()

how to get data from entry widget

i want my program to get the information from the ans entry widget and use it in the if and elif statment
def goal():
root1 = Tk()
first_p_x = random.randint(1, 50)
first_p_y = random.randint(1, 50)
second_p_x = random.randint(1, 50)
second_p_y = random.randint(1, 50)
Label(root1, text=f'what is the slope of these two points ( {first_p_x} , {first_p_y} ) ( {second_p_x} , {second_p_y} )').grid(row=0, column=0, sticky='e')
ans = Entry(root1, width=30).grid(row=0, column=1,
padx=2, pady=2, sticky='we', columnspan=9)
delta_y = first_p_y - second_p_y
delta_x = first_p_x - second_p_x
a = Fraction(delta_y, delta_x)
if ans == 'help':
Label(root1, text=f"so first you set up the problem as {first_p_y}-{second_p_y} over {first_p_x}-{second_p_x}").grid(row=2, column=0, sticky='e')
Entry(root1, width=30).grid(row=2, column=1,
padx=2, pady=2, sticky='we', columnspan=9)
elif ans == a:
Label(root1, text="Thats correct nice job").grid(row=1, column=0, sticky='e')
Button(root1, text="Submit", width=15, command=root1.destroy).grid(row=3, column=1, sticky='e', padx=2, pady=2)
you can use the .get() method here is a example you should add a entry button like in the code below
def ans_func():
ans_data = ans.get()
if ans_data == 'help'
#your function
elif:
#your function
and to the button add command='ans_func'

How Can I write Python code for Temperature Convert to C orF using Frames, Entry Box and Label?

from tkinter import*
def convert2c():
try:
f = float(tempIN.get())
c = (f-32)*5.0/9.0
tempOUTc.set(c)
except ValueError:
pass
def convert2f():
try:
c = float(tempIN.get())
f = c*9.0/5.0 + 32
tempOUTf.set(f)
except ValueError:
pass
root = Tk()
f = root
root.title("Temperature Converter")
root.geometry('{}x{}'.format(500,200))
topFrm = Frame(root, width=500, height=80, bg="#e01111")
midFrm = Frame(root, width=500, height=150, bg="#795fb5")
btmFrm = Frame(root, width=500, height=100)
btmL = Frame(btmFrm, width=250, height=100, bg="#4117a5")
btmR = Frame(btmFrm, width=250, height=100, bg="#3f454f")
topFrm.grid(row=0, sticky="W")
midFrm.grid(row=1)
btmFrm.grid(row=3)
btmL.grid(row=2, column=0)
btmR.grid(row=2, column=2)
tempIN = StringVar()
tempOUTc = StringVar()
tempOUTf = StringVar()
Label(f, text="Temperature Converter\n A number in temperature degree is converted into another as one of the button is clicked").grid(column=0, row=0)
Label(f, text="Enter a Temperature").grid(column=0, row=1)
Entry(f, textvariable=tempIN, width=10) .grid(column=0, rowspan=1, row=1, sticky=W)
Button(f, text=" to Celsius", command=convert2c) .grid(column=0, row=3, sticky=W)
Button(f, text=" to Fahrenheit", command=convert2f) .grid(column=1, row=3, sticky=W)
Label(f, textvariable=tempOUTc) .grid(column=2, row=1, sticky=W)
Label(f, textvariable=tempOUTf) .grid(column=2, row=2, sticky=W)
root.mainloop()

Resources