My first post, so I apologize as I learn to use this. Also, I am sure my code is very jumbled and rudimentary, but I am not here to get someone to re-write my code. I have a question about how a widget is behaving and an error code I am getting.
I currently have two frames in a mainWindow, and when you click a button labeled "New", a small window (newWindow) pops up that has a registration form, and a button labeled "Register" to write the form data to a .txt file.
The problem I am having is that if I do not define where the button should go, it appears in the mainWindow. If I specify for it to appear in the newWindow, it does not appear and throws me the following error:
File
"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/init.py",
line 1507, in nametowidget
w = w.children[n] KeyError: '!button2'
Here is my code (get ready for a mess!):
from tkinter import *
from tkinter import ttk
from time import strftime
from tkmacosx import SFrame, Button
import tkinter as tk
mainWindow = Tk()
mainWindow.title('BATCO Main')
def createWindow():
#When createWindow() is called, the following code is executed, starting with creating the window object itself, which is set to the Tk() widget caller
newWindow = Tk()
# Add title of window
newWindow.title('Patron Entry')
# Set from and geometry of the Button (widthxheight+XPOS+YPOS)
newWindow.geometry('500x350+100+200')
# THIS PART CREATES AND APPENDS THE FILE FOR STORING NAMES:
def saveInfo():
# Defines Variables(3) for the "get" Method that will take from the StringVar Variables(2) above:
fname_info = fname.get()
mname_info = mname.get()
lname_info = lname.get()
suffix_info = suffix.get()
addr1_info = addr1.get()
addr2_info = addr2.get()
city_info = city.get()
state_info = state.get()
zipcode_info = zipcode.get()
print(fname_info, mname_info, lname_info, suffix_info, addr1_info, addr2_info, city_info, state_info, zipcode_info)
# This starts by opening the file 'patrons.txt' and assigns it to the file Variable. It uses the Arg 'a' which stands for Append, so it will add to the file.
file = open('patrons.txt', 'a')
# Once the file is open, write to it using the write method on the Variable file. The Write method accepts one Arg, so I have to use the + Operator to Concatenate text.
file.write (fname_info + ',')
file.write (mname_info + ',')
file.write (lname_info + ',')
file.write (suffix_info + ',')
file.write (addr1_info + ',')
file.write (addr2_info + ',')
file.write (city_info + ',')
file.write (state_info + ',')
file.write (zipcode_info + ';\n')
file.close ()
print (fname_info, 'has been registered')
# Clears the fields in the form
fname_entry.delete(0, END)
mname_entry.delete(0, END)
lname_entry.delete(0, END)
suffix_entry.delete(0, END)
addr1_entry.delete(0, END)
addr2_entry.delete(0, END)
city_entry.delete(0, END)
state_entry.delete(0, END)
zipcode_entry.delete(0, END)
# This code closes the window after entry
newWindow.destroy()
# End of saveInfo function
# Creating basic text that is formatted to be a header at the top of the window
lbl = Label(newWindow, text = 'Create Record', bg = 'light gray', fg = 'gray', width = '50', font = ('Arial', 17))
lbl.place(x=0, y=0)
# Defining Variables(1) for the text box labels:
fname_text = Label(newWindow, text = 'First Name', fg = 'gray', font = ('Arial', 12))
mname_text = Label(newWindow, text = 'Middle name', fg = 'gray', font = ('Arial', 12))
lname_text = Label(newWindow, text = 'Last Name', fg = 'gray', font = ('Arial', 12))
suffix_text = Label(newWindow, text = 'Suffix', fg = 'gray', font = ('Arial', 12))
addr1_text = Label(newWindow, text = 'Address 1', fg = 'gray', font = ('Arial', 12))
addr2_text = Label(newWindow, text = 'Address 2', fg = 'gray', font = ('Arial', 12))
city_text = Label(newWindow, text = 'City', fg = 'gray', font = ('Arial', 12))
state_text = Label(newWindow, text = 'State', fg = 'gray', font = ('Arial', 12))
zip_text = Label(newWindow, text = 'Zip', fg = 'gray', font = ('Arial', 12))
# Placing text box labels:
fname_text.place(x = 15, y = 50)
mname_text.place(x = 155, y = 50)
lname_text.place(x = 295, y = 50)
suffix_text.place(x = 435, y = 50)
addr1_text.place(x = 15, y = 100)
addr2_text.place(x = 15, y = 150)
city_text.place(x = 15, y = 200)
state_text.place(x = 318, y = 200)
zip_text.place(x = 367, y = 200)
# Defining and formatting Variables(2) for the data entered INTO the Entry boxes:
fname = StringVar()
mname = StringVar()
lname = StringVar()
suffix = StringVar()
addr1 = StringVar()
addr2 = StringVar()
city = StringVar()
state = StringVar()
zipcode = StringVar()
# Defining the Variables(3) for the Entry boxes:
fname_entry = Entry(newWindow, textvariable = fname, width = 14)
mname_entry = Entry(newWindow, textvariable = mname, width = 14)
lname_entry = Entry(newWindow, textvariable = lname, width = 14)
suffix_entry = Entry(newWindow, textvariable = suffix, width = 5)
addr1_entry = Entry(newWindow, textvariable = addr1, width = 51)
addr2_entry = Entry(newWindow, textvariable = addr2, width = 51)
city_entry = Entry(newWindow, textvariable = city, width = 32)
state_entry = Entry(newWindow, textvariable = state, width = 3)
zipcode_entry = Entry(newWindow, textvariable = zipcode, width = 13)
`enter code here`# Placing the Entry boxes:
fname_entry.place(x=15, y = 69)
mname_entry.place(x=155, y = 69)
lname_entry.place(x=295, y = 69)
suffix_entry.place(x=435, y = 69)
addr1_entry.place(x=15, y = 119)
addr2_entry.place(x=15, y = 169)
city_entry.place(x=15, y = 219)
state_entry.place(x=318, y = 219)
zipcode_entry.place(x=360, y = 219)
# Creates a Button and assigns it to the Variable: register. It is a gray, borderless button that when clicked, calls the saveInfo function.
register = Button(text = "REGISTER", bordercolor = 'gray', padx = 10, pady = 5, background='#BDBDBD', borderless = 'true', relief = 'groove', command = saveInfo)
# Places the Button
register.place (in_=newWindow, x = 200, y = 275)
newWindow.mainloop()
# End of createWindow function
style1 = ttk.Style()
style2 = ttk.Style()
style3 = ttk.Style()
style1.configure('topFrame.TFrame', background='green', borderwidth=4, relief='raised')
style2.configure('bottomFrame.TFrame', background = 'blue', borderwidth=6, relief = 'raised')
style3.configure('SrchLabel.TLabel')
eFrame = ttk.Frame(mainWindow, width=1060, height=200, style='topFrame.TFrame').grid()
rFrame = ttk.Frame(mainWindow, width=1060, height=600, style='bottomFrame.TFrame').grid()
# eFrame: Title text shown before the search terms entry box
srchFrame = ttk.Label(mainWindow, style = 'SrchLabel.TLabel', text = 'Patron Search')
srchFrame.place (x='30', y='40')
# eFrame: Search terms entry box
srchVar = StringVar()
srchEntry = tk.Entry(eFrame, bd = '1', width = '35')
srchEntry.place (x='130', y='37')
# eFrame: Button to execute Search
srchButton = Button(eFrame, text = 'Search', height = 30, width = 60, bd = '1')
srchButton.place(x = '470', y = '35')
# eFrame: Button to create New Record
newButton = Button(eFrame, text = 'New', height = 30, width = 60, bd = '1', command = createWindow)
newButton.place(x = '550', y = '35')
# rFrame: TAB Window Frame = from ttk Notebook
tabControl = ttk.Notebook(rFrame, width = 995, height = 528, style = 'rTabs.TNotebook')
# rFrame: TAB Elements
tab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)
tab3 = ttk.Frame(tabControl)
tab1=Frame(tabControl, background="#ffffff")
tab1.pack()
tab2=Frame(tabControl, background="#ffffff")
tab2.pack()
tab3=Frame(tabControl, background="#ffffff")
tab3.pack()
# rFrame: TAB Titles and Window placement
tabControl.add(tab1, text ='Patron')
tabControl.add(tab2, text ='Orders')
tabControl.add(tab3, text = 'Donations')
tabControl.place(x='5', y='205')
# TAB 1 Content
ttk.Label(tab1, text ='Patron Data').grid(column = 0, row = 0, padx = 30, pady = 30)
# TAB 2 Content
ttk.Label(tab2, text ='Order History and Info').grid(column = 0, row = 0, padx = 30, pady = 30)
# TAB 3 Content
ttk.Label(tab3, text ='Donation Info').grid(column = 0, row = 0, padx = 30, pady = 30)
# mainWindow: MENUBAR
menubar = Menu(mainWindow)
# mainWindow: Filemenu
file = Menu(menubar, tearoff = 1)
menubar.add_cascade(label ='File', menu = file)
file.add_command(label ='New File', command = None)
file.add_command(label ='Open...', command = None)
file.add_command(label ='Save', command = None)
file.add_separator()
file.add_command(label ='Exit', command = mainWindow.destroy)
# mainWindow: Editmenu
edit = Menu(menubar, tearoff = 1)
menubar.add_cascade(label ='Edit', menu = edit)
edit.add_command(label ='Cut', command = None)
edit.add_command(label ='Copy', command = None)
edit.add_command(label ='Paste', command = None)
edit.add_command(label ='Select All', command = None)
edit.add_separator()
edit.add_command(label ='Find...', command = None)
edit.add_command(label ='Find again', command = None)
# mainWindow: Helpmenu
help_ = Menu(menubar, tearoff = 1)
menubar.add_cascade(label ='Help', menu = help_)
help_.add_command(label ='Tk Help', command = None)
help_.add_command(label ='Demo', command = None)
help_.add_separator()
help_.add_command(label ='About Tk', command = None)
mainWindow.config(menu = menubar)
mainWindow.mainloop()
Again, I am not looking for advice on how to write better code, as I am just learning (2 weeks in). However any help you can provide in letting me know what I am doing wrong and where I can find an answer would be greatly appreciated!
Thanks in advance!
Related
i am making a movie recommendation GUI with the help of a dataset. For that, i need the value selected from the list by clickng on the recommedation button but i am not able to figure out to do so.
from tkinter import *
import pandas as pd
window = Tk()
window.config(background = 'white')
window.geometry('700x500')
title = Label(text = 'Movie Recommendation', font = ('times new roman',20),background = 'white')
title.pack()
label = Label(text = '**********************', font = ('times new roman',17),background = 'white' )
label.pack()
label = Label(text = 'Movie List :', font = ('times new roman',17),background = 'white' )
label.place(x = 5, y =66)
scroll_bar = Scrollbar(window)
scroll_bar.pack(side = RIGHT, fill = Y)
list = Listbox(window, yscrollcommand = scroll_bar.set, height = 21, width = 40, background = 'white', foreground = 'black' )
for i in df['title']:
list.insert(END,i)
list.place(x=5,y=105)
rec = Label(text = 'Recommended Movies :', font = ('times new roman',17),background = 'white')
rec.place(x = 300, y = 66)
def selected_item():
print(list.get(ANCHOR))
# selected = Label(text = selected_item(),font = ('times new roman',15))
# selected.place(x=300,y = 96)
def movie():
button = Button(text = "Recommendation",foreground='black', command = selected_item,background = 'white')
button.place(x=5,y=460)
movie()
window.mainloop()
this is my code.
i tried everything i could think of but i am new to coding. thank you.
(If anyone has seen my previous question, I found a way to save the row indexes and use them in the delete function :3)
Is there a way to stop/delete a running function/table on a button click? I am making a simple customer registration program which saves data from text fields (cID, custName, custEmail, and custBday) and deletes a selected row. My problem is that whenever I delete a row, the last row somehow leaves/lags behind creating this duplicate whenever a row is deleted. Any suggestions or is there something I've done wrong or I've missed?
My Code:
from tkinter import *
from tkinter import messagebox
import tkinter as tk
at = False
dotcom = False
list = [['ID', 'NAME', 'EMAIL', 'BIRTHDATE']]
recentIndex = []
ID = 1
storedIndex = 0
def callback(event):
custid.config(state=NORMAL)
custid.delete('1.0', END)
custid.insert(1.0, list[event.widget._values][0])
custid.config(state=DISABLED)
cName.set(list[event.widget._values][1])
cEmail.set(list[event.widget._values][2])
birthdate.set(list[event.widget._values][3])
indexPosition = event.widget._values
recentIndex.append(indexPosition)
print(recentIndex)
def createTable():
for i in range(len(list)):
for j in range(len(list[0])):
mgrid = tk.Entry(window, width = 10, bg= 'yellow')
mgrid.insert(tk.END, list[i][j])
mgrid._values= i
mgrid.grid (row = i + 5,column = j + 5)
mgrid.bind("<Button-1>", callback)
def delete():
try:
list.pop(recentIndex[-1])
if recentIndex[-1] > 0 or NONE:
msgbox("Data Delete", "Record")
createTable()
else:
msgbox("No Data Selected", "record")
return
except:
msgbox("No Data Selected", "record")
def save ():
custid.config(state= NORMAL)
initialValue = int(custid.get('1.0', END))
custid.delete('1.0', END)
list.append([ID, custName.get(), custEmail.get(), custBday.get()])
custid.insert(1.0, initialValue + 1)
custid.config(state=DISABLED)
createTable()
msgbox("Saved", "Record")
ID = ID + 1
def msgbox (msg, titlebar):
messagebox.showinfo(title = titlebar, message=msg)
def products():
window = Tk()
window.title("Products Form")
window.geometry("550x400")
window.configure(bg="orange")
window = Tk()
window.title("Sample Window")
window.geometry("550x400")
window.configure(bg="orange")
menubar = Menu(window)
filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Products", command=products)
filemenu.add_command(label="Orders")
filemenu.add_separator()
filemenu.add_command(label="Close", command = window.quit)
window.config(menu=menubar)
labelTitle = Label(window, text="Customer Registration System", width=30, height=1, bg="yellow", anchor= "center")
labelTitle.config(font=("Courier", 10))
labelTitle.grid(column=2, row=1)
labelID = Label(window, text="Customer ID", width = 20, height = 1, bg = "yellow")
labelID.grid(column=1, row=2)
cID = StringVar()
custid = Text(window, width=15, height=1)
custid.grid(column=2, row=2)
custid.insert(1.0, "1")
custid.config(state = DISABLED)
labelNameCheck = Label(window, text="Last Name, First Name", width = 20, height = 1, bg = "yellow")
labelNameCheck.grid(column=3, row=3)
labelName = Label(window, text="Customer Name", width = 20, height = 1, bg = "yellow")
labelName.grid(column=1, row=3)
cName = StringVar()
custName = Entry(window, textvariable = cName)
custName.grid(column=2, row=3)
labelEmail = Label(window, text="Customer Email", width = 20, height = 1, bg = "yellow")
labelEmail.grid(column=1, row=4)
cEmail = StringVar()
custEmail = Entry(window, textvariable = cEmail)
custEmail.grid(column=2, row=4)
custEmail.bind("<KeyRelease>", keyup)
labelEmail = Label(window, text="[a-z]#[a-z].com", width = 20, height = 1, bg = "yellow")
labelEmail.grid(column=3, row=4)
labelBday = Label(window, text="Customer Birthdate", width = 20, height = 1, bg = "yellow")
labelBday.grid(column=1, row=5)
birthdate= StringVar()
custBday = Entry(window, textvariable = birthdate)
custBday.grid(column=2, row=5)
custBday.bind("<KeyRelease>", keyupBdate)
birthdateCheck = Label(window, text="mm/dd/yyyy", width = 20, height = 1, bg = "yellow")
birthdateCheck.grid(column=3, row=5)
savebtn = Button(text = "Save", command = save)
savebtn.grid(column=1)
deletebtn = Button(text = "Delete", command = delete)
deletebtn.grid(column=1)
window.mainloop()
You need to delete current displayed records before showing updated records inside createTable(). Also better create a frame for showing the records, so that it is more easier to clear the displayed records:
def createTable():
# clear current displayed records
for w in tableFrame.winfo_children():
w.destroy()
# populate records
for i in range(len(list)):
for j in range(len(list[0])):
mgrid = tk.Entry(tableFrame, width = 10, bg= 'yellow') # use tableFrame as parent
mgrid.insert(tk.END, list[i][j])
mgrid._values= i
mgrid.grid (row = i,column = j)
mgrid.bind("<Button-1>", callback)
...
# frame for showing records
tableFrame = Frame(window)
tableFrame.grid(row=5, column=5)
...
I am new to Python, trying to make the Launch TFL App button open another GUI called "Menu GUI" but I don't know what to do for the def open_Menu(): function below. I want to use the popup GUI below as a launcher which takes the user to my main GUI. The only problem with the code below is that the button for launch TFL app doesn't do anything when you click it.
Here's my current code :
from tkinter import *
root = Tk()
root.title('TFL App')
p = Label(root, text = "TFL Journey Planner", height = "18", width = "250", bg = 'brown', fg =
'white',
font = ('Helvetica', '20', 'bold', 'italic'))
p.pack()
root.configure(bg = 'brown')
root.geometry('400x700')
photo = PhotoImage(file = 'trainstation.png')
label = Label(root, image = photo)
label.pack()
****#Buttons****
def open_Menu():
pass
Button1 = Button(root, text = "Launch TFL App", command = open_Menu, bg = "black", fg = 'white', padx
= 40,
pady = 10,
font = ('Calibri Light', '15', 'bold'))
Button1.pack(padx = 25, pady = 0)
Button2 = Button(root, text = "Exit ", command = root.destroy, bg = "black", fg = 'white', padx = 65,
pady = 8,
font = ('Calibri Light', '15', 'bold'))
Button2.pack(padx = 25, pady = 10)
root.mainloop()
How can I implement open_menu()
The code below is for my Main GUI which should open through the PopUp GUI above but the button on the PopUp GUI is not working.
from tkinter import *
def find():
# get method returns current text
# as a string from text entry box
From = From_field.get()
To = To_field.get()
travel_modes = mode_field.get()
# Calling result() Function
result(From, To, travel_modes)
# Function for inserting the train string
# in the mode_field text entry box
def train():
mode_field.insert(10, "train")
# Function for clearing the contents
def del_From():
From_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
def del_To():
To_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
def del_modes():
mode_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
def delete_all():
From_field.delete(0, END)
To_field.delete(0, END)
mode_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
# Driver code
if __name__ == "__main__":
# Create a GUI root
root = Tk()
# Set the background colour of GUI root
root.configure(background = 'light blue')
# Set the configuration of GUI root
root.geometry("600x400")
# Created a welcome to distance time calculator label
headlabel = Label(root, text = 'Welcome to your TFL Journey Planner',
fg = 'white', bg = "dark red", height = "0", width = "30",
font = ('calibri light', '19', 'italic'))
# Created a From: label
label1 = Label(root, text = "From:",
fg = 'white', bg = 'black')
# Created a To: label
label2 = Label(root, text = "To:",
fg = 'white', bg = 'black')
# Created a Distance: label
label4 = Label(root, text = "Distance:",
fg = 'white', bg = 'black')
# Created a Duration: label
label5 = Label(root, text = "Duration:",
fg = 'white', bg = 'black')
label6 = Label(root, text = "Choose travelling mode Below: ",
fg = 'white', bg = 'black')
headlabel.grid(row = 0, column = 1)
label1.grid(row = 1, column = 0, sticky = "E")
label2.grid(row = 2, column = 0, sticky = "E")
label4.grid(row = 7, column = 0, sticky = "E")
label5.grid(row = 8, column = 0, sticky = "E")
label6.grid(row = 3, column = 1)
# Created a text entry box
# for filling or typing the data.
From_field = Entry(root)
To_field = Entry(root)
mode_field = Entry(root)
distance_field = Entry(root)
duration_field = Entry(root)
From_field.grid(row = 1, column = 1, ipadx = "100")
To_field.grid(row = 2, column = 1, ipadx = "100")
mode_field.grid(row = 5, column = 1, ipadx = "50")
distance_field.grid(row = 7, column = 1, ipadx = "100")
duration_field.grid(row = 8, column = 1, ipadx = "100")
# CLEAR Button and attached
# to del_source function
button1 = Button(root, text = "Clear", bg = "light grey",
fg = "black", command = del_From)
# Create a CLEAR Button and attached to del_destination
button2 = Button(root, text = "Clear", bg = "light grey",
fg = "black", command = del_To)
# Create a RESULT Button and attached to find function
button3 = Button(root, text = "Result",
bg = "black", fg = "white",
command = find)
# Create a CLEAR ALL Button and attached to delete_all function
button4 = Button(root, text = "Clear All",
bg = "light grey", fg = "black",
command = delete_all)
# Create a Train Button and attached to train function
button5 = Button(root, text = "Train",
bg = "light grey", fg = "black",
command = train)
# Create a CLEAR Button and attached to del_modes function
button6 = Button(root, text = "Clear",
fg = "black", bg = "light grey",
command = del_modes)
button1.grid(row = 1, column = 2)
button2.grid(row = 2, column = 2)
button3.grid(row = 6, column = 1)
button4.grid(row = 9, column = 1)
button5.grid(row = 4, column = 1)
button6.grid(row = 5, column = 2)
root.mainloop()
Here is a solution using from subprocess import call. All you have to do is replace 'YOUR_FILE_NAME' with... your file name :D
from tkinter import *
from subprocess import call
root=Tk()
root.geometry('200x100')
frame = Frame(root)
frame.pack(pady=20,padx=20)
def open_Menu():
call(["python", "YOUR-FILE-NAME.py"])
btn=Button(frame,text='Open File',command=Open)
btn.pack()
root.mainloop()
What it will look like:
I hope this works for you :D
I am new to this tkinter menu. I am trying to upload and display an excel file by using the 'filemenu' in the menubar and 'btnNew' in the toolbar menu.
The application did run but it does not display my excel file after I browse the file. The application only display the datatypes of each variable in the excel file.
import pandas as pd
import xlrd
import tkinter as tk
from tkinter import Frame, Menu, Button, Label, Canvas
from tkinter import LEFT, RIGHT, TOP, BOTTOM, X, FLAT, RAISED
from tkinter import filedialog
from tkinter import ttk
root = tk.Tk() #main method 1 - create main window (parent window)
root.title("Data Visualisation")
width = 1000
height = 500
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry('%dx%d+%d+%d' % (width, height, x, y))
root.resizable(1,1)
def browseFile():
global workbook, copyWorkbook, excel_file, sheetName, worksheet
fileName = filedialog.askopenfilename(initialdir = '/', title = 'New File', filetypes = (('excel file', '.xlsx'), ('excel file', '.xls'), ('all files', '*.*')))
excel_file = pd.ExcelFile(fileName)
workbook = xlrd.open_workbook(fileName)
sheetCount = workbook.nsheets
#Create tabs
sheetName = []
tab = []
for x in range(workbook.nsheets):
tab.append(ttk.Frame(tabControl))
sheetName = workbook.sheet_names()
tabControl.add(tab[x], text = sheetName[x])
df_table = excel_file.parse(sheetName[x])
print(df_table.dtypes)
lblTable = Label(tab[x], text = df_table.to_string(index = False)).grid()
btnGraph = Button(tab[x], text = "Graph").grid(sticky = 'w', column = 1, row = 5)
##MENU BAR
menubar = Menu(root)
root.config(menu = menubar)
#FILE MENU
filemenu = Menu(menubar, bg = '#BFBFBF', tearoff = 0)
menubar.add_cascade(label = 'File', menu = filemenu)
filemenu.add_command(label = 'New', compound = LEFT, command = browseFile)
filemenu.add_command(label = 'Open...', compound = LEFT)
filemenu.add_separator()
filemenu.add_command(label = 'Quit', compound = LEFT, command = root.quit)
#SEARCH MENU
searchmenu = Menu(menubar, bg = '#BFBFBF')
menubar.add_cascade(label = 'Search', menu = searchmenu)
searchmenu.add_command(label = 'Find...', compound = LEFT)
searchmenu.add_command(label = 'Replace...', compound = LEFT)
#HELP MENU
helpmenu = Menu(menubar, bg = '#BFBFBF')
menubar.add_cascade(label = 'Help', menu = helpmenu)
helpmenu.add_command(label = 'About', compound = LEFT)
##TOOLBAR MENU
toolbar = Frame(root, bd = 1, relief = RAISED)
#To browse excel file
btnNew = Button(toolbar, text = 'New', compound = TOP, relief = FLAT, activebackground = '#ADD8E6', padx = 20, pady = 2, command = browseFile).pack(side = LEFT)
btnOpen = Button(toolbar, text = 'Open', compound = TOP, relief = FLAT, activebackground = '#ADD8E6', padx = 10, pady = 2).pack(side = LEFT)
btnFind = Button(toolbar, text = 'Find', compound = TOP, relief = FLAT, activebackground = '#ADD8E6', padx = 10, pady = 2).pack(side = LEFT)
btnReplace = Button(toolbar, text = 'Replace', compound = TOP, relief = FLAT, activebackground = '#ADD8E6', padx = 10, pady = 2).pack(side = LEFT)
btnQuit = Button(toolbar, text = 'Quit', compound = TOP, relief = FLAT, activebackground = '#ADD8E6', padx = 10, pady = 2, command = root.quit).pack(side = RIGHT)
toolbar.pack(side = TOP, fill = X)
###Tab Widget
tabControl = ttk.Notebook(menubar)
tabHome = ttk.Frame(tabControl)
tabControl.add(tabHome, text = "Home")
#All the automation Tab is pack here
tabControl.pack(expand = 1, fill = 'both', side = LEFT)
root.mainloop() #main method 2 - run the application
The application should display tabs and in each tab, it should contain each sheet from the excel file. All the tabs must be display after the toolbar menu.
I'm not sure what is the problem as is does not specify if there is any error in my code.
All feedback is welcomed as I am trying to learn how to make a better interface using python. Thank you for your help :D
You set the wrong parent to the frame tabControl.
Change:
tabControl = ttk.Notebook(menubar)
to:
tabControl = ttk.Notebook(root)
I'm trying to get all of my labels and input boxes to be shifted down to the middle of the screen using the .pack() method. I tried using
anchor = CENTER
with the.place() method but that made everything overlap in the center. How can I simply shift all of my widgets to the center of my Tkinter frame?
Here's my code:
from Tkinter import *
root = Tk()
root.minsize(width = 500, height = 500)
root.wm_title("Email Program v1.0")
def callback():
print ("Hello!")
#sign in - email
usernameLabel = Label(root, text = "Email:")
usernameLabel.pack(padx = 0, pady = 0)
usernameInput = Entry(root)
usernameInput.pack()
usernameInput.focus_set()
passwordLabel = Label(root, text = "Password:")
passwordLabel.pack()
passwordInput = Entry(root, show = "*", width = 20)
passwordInput.pack()
passwordInput.focus_set()
#submit email credentials - connect to the server
submitEmail = Button(root, text = "Submit", fg = "black", width = 10, command = callback)
submitEmail.pack()
root.mainloop()
I managed to put those labels and entries to the center using three frames, two without any content just to 'eat' space.
frame1 = Frame(root)
frame1.pack(expand=True)
frame2 = Frame(root)
usernameLabel = Label(frame2, text = "Email:")
usernameLabel.pack(padx = 0, pady = 0)
usernameInput = Entry(frame2)
usernameInput.pack()
usernameInput.focus_set()
passwordLabel = Label(frame2, text = "Password:")
passwordLabel.pack()
passwordInput = Entry(frame2, show = "*", width = 20)
passwordInput.pack()
passwordInput.focus_set()
submitEmail = Button(frame2, text = "Submit", fg = "black", width = 10, command\
= callback)
submitEmail.pack()
frame2.pack(anchor=CENTER)
frame3 = Frame(root)
frame3.pack(expand=True)
The simple solution is to put all the widgets in a frame, and then center the frame.