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)
Related
I have several larger tkinter / python program which I would like to incorporate into one program which would clear a frame when another program is called; each program currently being inside a function (I probably should use classes eventually when I understand them) and each of these function being displayed on a form being cleared of widgets from the previous if any do exist.
The code below is just a small trial for me to understand how to do this, but it's not working.
When I invoke the widget.destroy() function, it removes the frame (DisplayFrame) and does not clear the widgets inside it and hence not displaying the new widgets.
here is the current trial code:
#!/usr/bin/env python3
import tkinter as tk
from tkinter import *
from tkinter import ttk
#import pandas as pd
import MultiTempsP3
import datetime, time
from tkinter import messagebox
import sqlite3
from tkinter import colorchooser
from configparser import ConfigParser
import os
import csv
if os.environ.get('DISPLAY','') == "":
print('no display found.Using :0.0')
os.environ.__setitem__('DISPLAY',':0.0')
root = tk.Tk()
root.title("Kombucha Program")
root.geometry("1400x800")
root.minsize(width=900, height=600)
#root.maxsize(width=1400, height = 900)
root.grid_rowconfigure(3, weight=1)
root.grid_columnconfigure(2, weight=1)
root.configure( bg = '#000080' )
DisplayFrame = tk.Frame(root, width=1200, height = 630, bg = 'yellow') #0059b3')
DisplayFrame.grid(column=0,row=1, sticky = N, in_ = root)
rightFrame = tk.Frame(root, width = 120, height = 390, bg = 'white') # #000080
rightFrame.grid(column = 1, row = 0, pady = 10, padx = 10)
lblFrame = tk.Frame(root, height = 70, width = 670, bg = 'black')
lblFrame.grid(column = 0, row = 0, sticky =N, in_ = root)
##'W' stands for West = WrightFrmae (west fframe on the right of screen
#WrightFrame = tk.Frame(rightFrame, width = 70, height = 300, bg = 'green') # #000080
#WrightFrame.grid(column = 0, row = 1)
WidgetFrame = tk.Frame(root, height = 300, width = 120, bg = 'red') # #000080
WidgetFrame.grid(column=0,row=2, pady = 30)
fromTemp = MultiTempsP3.temps("65cd6bd")
lblTemp = Label(rightFrame, text=fromTemp).grid(row=1,column=0,pady=0 )
#lblTemp.pack()
def clearDisplayFrame():
for widgets in DisplayFrame.winfo_children():
widgets.destroy()
###***### - This section is in the right top little frame = rightFrame
state = "yes" ## delete this row and use below state=GPIO when on an RPi
#state = GPIO.input(17)
if state:
state_17="GPIO_17 (HeatPad) is On "
else:
state_17="GPIO_17 (HeatPad) is Off "
lblHeatPad = Label(rightFrame, text=state).grid(row=3,column=0,pady=0 ) #shows as text in the window
#lblHeatPad.pack() #organizes widgets in blocks before placing them in the parent.
###***### End of rightFrame widgets
def func_quit():
root.destroy()
def openData():
clearDisplayFrame()
print("I am inside openData()")
lbltrial=tk.Label(DisplayFrame,text="trial").grid(row=3, column=2)
def func_Temps():
clearDisplayFrame()
print("I am inside func_Temps()")
#DisplayFrame = tk.Frame(root, width=1200, height = 630, bg = 'yellow') #0059b3')
#DisplayFrame.grid(column=0,row=1, sticky = N, in_ = root)
lblSomething = tk.Label(DisplayFrame, text = "Open Temps").grid(row=2,column=2)
###***### This section is top of left = lblFrame
exitButton = tk.Button(lblFrame, text="Quit the Program", width = 12, command=root.destroy, bg= "magenta")
exitButton.grid(row = 0, column = 0, columnspan = 1, pady = 5, padx = 5)
dataButton = Button(lblFrame, text="Open Dates Window", command=openData).grid(row=0, column=1) ## the open refers to the above function
tempsButton= Button(lblFrame, text="Open Temps Info", command=func_Temps).grid(row=0, column=2)
###***### End of top left widget in lblFrame
mainloop()
As an answer, here is an approach that uses 2 frame and switches between them in the click of the switch. This is the way usually switching between frame is implemented in procedural programming, AFAIK:
from tkinter import *
root = Tk()
def change(frame):
frame.tkraise() # Raising the passed frame
window1 = Frame(root)
window2 = Frame(root)
window1.grid(row=0,column=0) # Grid in the same location so one will cover/hide the other
window2.grid(row=0,column=0)
# Contents inside your frame...
Label(window1,text='This is page 1',font=(0,21)).pack()
Label(window2,text='This is page 2',font=(0,21)).pack()
# Buttons to switch between frame by passing the frame as an argument
Button(root,text='Page 1',command=lambda: change(window1)).grid(row=1,column=0,stick='w')
Button(root,text='Page 2',command=lambda: change(window2)).grid(row=1,column=0,stick='e')
root.mainloop()
So instead of destroying all the items inside your frame, you should just raise the other frame, as destroyed widgets cannot be brought back.
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!
I have made "sticky notes" in python but how do I make the same open in another window when I press the new File (+ on the title bar) button? I thought of creating an object within the class but I don't think that's possible. Should I import and run similar file? Please suggest a method to do so. Suggestions to improve the code are welcomed.
Here's the code
from tkinter import *
import tkinter.scrolledtext as tkst
from tkinter import messagebox
from tkinter import font
class StickyNotes:
xclick = 0
yclick = 0
def __init__(self,master):
def get_pos(event):
self.xclick = event.x
self.yclick = event.y
def move_window(event):
master.geometry('+{0}+{1}'.format(event.x_root-self.xclick, event.y_root-self.yclick))
def another_window(event):
pass
def quit_window(event):
self.closebutton.config(relief = 'flat', bd = 0)
if(messagebox.askyesno('Delete Note?','Are you sure you want to delete this note?')):
master.destroy()
return
self.closebutton.config(relief = 'flat', bd = 0, bg = '#F8F7B6')
# master (root) window
master.overrideredirect(True)
master.geometry('250x250')
master.config(bg = '#838383')
master.resizable(True,True)
# titlebar
self.titlebar = Frame(root, bg = '#F8F796', relief = 'flat', bd = 2)
self.titlebar.bind('<Button-1>', get_pos)
self.titlebar.bind('<B1-Motion>', move_window)
self.titlebar.pack(fill = X, expand = 1, side = TOP)
self.closebutton = Label(self.titlebar, text = 'X', bg = '#F8F7B6', relief = 'flat')
self.closebutton.bind('<Button-1>', quit_window)
self.closebutton.pack(side = RIGHT)
self.newbutton = Label(self.titlebar, text = '+', bg = '#F8F7B6', relief = 'flat')
self.newbutton.pack(side = LEFT)
self.newbutton.bind('<Button-1>', another_window)
# main text area
self.mainarea = tkst.ScrolledText(master, bg = '#FDFDCA', font=('Comic Sans MS', 14, 'italic'), relief = 'flat', padx = 5, pady = 10)
self.mainarea.pack(fill = BOTH, expand = 1)
# frames to introduce shadows
self.shadow = Frame(root).pack(side=BOTTOM)
self.shadow = Frame(root).pack(side=RIGHT)
root = Tk()
root.attributes('-topmost', 'true')
sticky = StickyNotes(root)
root.mainloop()
You are using classes all wrong. One of the biggest advantages to using classes is the ability to steal code from Tkinter (or whatever GUI or framework you are trying to use). The Tkinter window class is called Toplevel, so you want to subclass that and use the class itself (named "self") for all your operations. I rewrote it for you:
from tkinter import *
import tkinter.scrolledtext as tkst
from tkinter import messagebox
from tkinter import font
class StickyNotes(Toplevel):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.xclick = 0
self.yclick = 0
# master (root) window
self.overrideredirect(True)
self.geometry('250x250+500+500')
self.config(bg = '#838383')
self.attributes('-topmost', 'true')
self.resizable(True,True)
# titlebar
self.titlebar = Frame(self, bg = '#F8F796', relief = 'flat', bd = 2)
self.titlebar.bind('<Button-1>', self.get_pos)
self.titlebar.bind('<B1-Motion>', self.move_window)
self.titlebar.pack(fill = X, expand = 1, side = TOP)
self.closebutton = Label(self.titlebar, text = 'X', bg = '#F8F7B6', relief = 'flat')
self.closebutton.bind('<Button-1>', self.quit_window)
self.closebutton.pack(side = RIGHT)
self.newbutton = Label(self.titlebar, text = '+', bg = '#F8F7B6', relief = 'flat')
self.newbutton.pack(side = LEFT)
self.newbutton.bind('<Button-1>', self.another_window)
# main text area
self.mainarea = tkst.ScrolledText(self, bg = '#FDFDCA', font=('Comic Sans MS', 14, 'italic'), relief = 'flat', padx = 5, pady = 10)
self.mainarea.pack(fill = BOTH, expand = 1)
# frames to introduce shadows
self.shadow = Frame(self).pack(side=BOTTOM)
self.shadow = Frame(self).pack(side=RIGHT)
def get_pos(self, event):
self.xclick = event.x
self.yclick = event.y
def move_window(self, event):
self.geometry('+{0}+{1}'.format(event.x_root-self.xclick, event.y_root-self.yclick))
def another_window(self, event):
sticky = StickyNotes(root)
def quit_window(self, event):
self.closebutton.config(relief = 'flat', bd = 0)
if(messagebox.askyesno('Delete Note?','Are you sure you want to delete this note?')):
self.destroy()
return
self.closebutton.config(relief = 'flat', bd = 0, bg = '#F8F7B6')
root = Tk()
root.withdraw()
sticky = StickyNotes(root) # make the first note.
root.mainloop()
I am trying to build a xml parser in python, i start to build gui framework, and here i need to create some forms to save some settings values. I manage to make it work and save some values to txt files for startup. But what ever i tried i can't manage to close the settings form when i click button. i need to close it with the x on the window. i can't find the root of the issue.
what i am trying to do is, when i click Cancel, form will be closed. if i click Save, form will first save data then close.
thanks a lot for your supports.
my code is as follows:
try:
# for Python2
print ("Importing for py2");
from Tkinter import * ## notice capitalized T in Tkinter
import tkFileDialog
except ImportError:
# for Python3
print ("Importing for py2 Failed !!!!");
print ("Importing for py3");
from tkinter import *
from tkinter import filedialog
from tkinter.scrolledtext import ScrolledText
from tkinter import messagebox
mainform = Tk()
mainform.minsize(300,100)
mainform.geometry('{}x{}'.format(800, 600))
mainform.title("OVF Template Parser - By Gurhan Cagin (R) 2018")
textPad = ScrolledText(mainform, width=100, height=80)
textPad.pack()
## functions and procdures
def donothing():
x = 0
def quit():
if messagebox.askokcancel("Quit", "Do you really want to quit?"):
exit()
def about_command():
label = messagebox.showinfo("About", "Nokia OVF Template Parser \nCopyright 2018 \nNo rights left to reserve")
def open_command():
file = filedialog.askopenfile(parent=mainform, mode='rb', title='Select a file')
if file != None:
contents = file.read()
textPad.insert('1.0',contents)
file.close()
def SettingsFormFxn():
settingsForm = Tk()
settingsForm.minsize(300,100)
settingsForm.geometry('{}x{}'.format(750, 550))
settingsForm.title("Settings for the devault values")
## Frames
top_frame = Frame(settingsForm, width = 740, height = 50, pady = 3)
bottom_frame = Frame(settingsForm, width = 740, height = 50, pady = 3)
settingsForm.grid_rowconfigure(1, weight=1)
settingsForm.grid_columnconfigure(0, weight=1)
top_frame.grid(row=0, sticky="ew")
bottom_frame.grid(row = 4, sticky = "e")
b1 = Label(top_frame, text = "CPU per Core in Ghz:")
b1.grid(row = 0, column = 0)
entryText = StringVar(settingsForm, "2.1")
e1 = Entry(top_frame, textvariable = entryText, width = 5)
e1.grid(row = 0, column = 2)
def SaveFxn():
with open("settings.txt", "w") as f:
f.write(e1.get() + "\n")
##f.write(ent2.get() + "\n")
def CancelFxn():
settingsForm.destroy
cancel = Button(bottom_frame, text = "Cancel", command = CancelFxn, pady = 10, padx = 10,activebackground='grey',activeforeground='#AB78F1',bg='#e87474',highlightcolor='red')
cancel.grid(row = 0, column = 10)
save = Button(bottom_frame, text = "Save", command = SaveFxn, pady = 10, padx = 10)
save.grid(row = 0, column = 11)
settingsForm.mainloop()
## EOF FXNS
## Menu Definitions
menubar = Menu(mainform)
## File Menu
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label = "Open", command = open_command)
filemenu.add_separator()
filemenu.add_command(label="Exit", command = quit)
menubar.add_cascade(label="File", menu=filemenu)
## Settings Menu
settingsmenu = Menu(menubar, tearoff = 0)
settingsmenu.add_command(label = "Settings", command = SettingsFormFxn)
menubar.add_cascade(label="Settings",menu=settingsmenu)
## About Menu
aboutmenu = Menu(menubar, tearoff = 0)
aboutmenu.add_command(label = "About", command = about_command)
menubar.add_cascade(label="Help", menu=aboutmenu)
mainform.config(menu=menubar)
## EOF Menu Definitions
## Main loop
mainloop()
You forgot your parenthesis when trying to call settingsForm.destroy.
def CancelFxn():
settingsForm.destroy()
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.