Cannot create menu AttributeError: 'Frame' object has no attribute 'tk_menuBar' - python

I am using the following snippet from a tutorial of Tkinter to create a Gui with a menu Bar. I copied exactly how it was in the tutorial:
from tkinter import *
from tkinter import Menu
from tkinter import Menubutton
def new_file():
pass
def open_file():
pass
def stub_action():
pass
def makeCascadeMenu():
CasBtn = Menubutton(mBar, text='Cascading Menus', underline=0)
CasBtn.pack(side=LEFT, padx="2m")
CasBtn.menu = Menu(CasBtn)
CasBtn.menu.choices = Menu(CasBtn.menu)
CasBtn.menu.choices.wierdones = Menu(CasBtn.menu.choices)
CasBtn.menu.choices.wierdones.add_command(label='Stockbroker')
CasBtn.menu.choices.wierdones.add_command(label='Quantity Surveyor')
CasBtn.menu.choices.wierdones.add_command(label='Church Warden')
CasBtn.menu.choices.wierdones.add_command(label='BRM')
CasBtn.menu.choices.wierdones.add_command(label='Wooden Leg')
CasBtn.menu.choices.wierdones.add_command(label='Hire Purchase')
CasBtn.menu.choices.wierdones.add_command(label='Dead Crab')
CasBtn.menu.choices.wierdones.add_command(label='Tree Surgeon')
CasBtn.menu.choices.wierdones.add_command(label='Filling Cabinet')
CasBtn.menu.choices.wierdones.add_command(label='Goldfish')
CasBtn.menu.choices.wierdones.add_command(label='Is it a ...')
CasBtn.menu.choices.add_cascade(label='Is it a ...',
menu=CasBtn.menu.choices.wierdones)
CasBtn.menu.add_cascade(label='Scipts', menu=CasBtn.menu.choices)
CasBtn['menu'] = CasBtn.menu
return CasBtn
def makeCheckButtonMenu():
ChkBtn = Menubutton(mBar, text = 'Checkbutton Menus', underline=0)
ChkBtn.pack(side=LEFT, padx='2m')
ChkBtn.menu = Menu(ChkBtn)
ChkBtn.menu.add_checkbutton(label='Doug')
ChkBtn.menu.add_checkbutton(label='Dinsdale')
ChkBtn.menu.add_checkbutton(label='Stig O\'Tracy')
ChkBtn.menu.add_checkbutton(label='Vince')
ChkBtn.menu.add_checkbutton(label='Gloria Pules')
ChkBtn.menu.invoke(ChkBtn.menu.index('Dinsdale'))
ChkBtn['menu'] = ChkBtn.menu
return ChkBtn
def makeRadiobuttonMenu():
RadBtn = Menubutton(mBar, text='Radiobutton Menus', underline=0)
RadBtn.pack(side=LEFT, padx='2m')
RadBtn.menu = Menu(RadBtn)
RadBtn.menu.add_radiobutton(label='metonymy')
RadBtn.menu.add_radiobutton(label='zeugmatists')
RadBtn.menu.add_radiobutton(label='synechdotists')
RadBtn.menu.add_radiobutton(label='axiomists')
RadBtn.menu.add_radiobutton(label='anagogists')
RadBtn.menu.add_radiobutton(label='catachresis')
RadBtn.menu.add_radiobutton(label='periphrastic')
RadBtn.menu.add_radiobutton(label='litotes')
RadBtn.menu.add_radiobutton(label='circumlocutors')
RadBtn['menu'] = RadBtn.menu
return RadBtn
def makeDisabledMenu():
Dummy_button = Menubutton(mBar, text='Disabled Menu', underline=0)
Dummy_button.pack(side=LEFT, padx='2m')
Dummy_button["state"] = DISABLED
return Dummy_button
def makeCommandMenu():
CmdBtn = Menubutton(mBar, text='Button Commands', underline=0)
CmdBtn.pack(side=LEFT, padx="2m")
CmdBtn.menu = Menu(CmdBtn)
CmdBtn.menu.add_command(label="Undo")
CmdBtn.menu.entryconfig(0, state=DISABLED)
CmdBtn.menu.add_command(label='New...', underline=0, command=new_file)
CmdBtn.menu.add_command(label='Open...', underline=0, command=open_file)
CmdBtn.menu.add_command(label='Wild Font', underline=0,
font=('Tempus Sans ITC', 14), command=stub_action)
#CmdBtn.menu.add_command(bitmap="#bitmaps/RotateLeft")
CmdBtn.menu.add('separator')
CmdBtn.menu.add_command(label='Quit', underline=0,
background='white', activebackground='green',
command=CmdBtn.quit)
CmdBtn['menu'] = CmdBtn.menu
return CmdBtn
root = tkinter.Tk()
mBar = Frame(root, relief=RAISED, borderwidth=2)
mBar.pack(fill=X)
CmdBtn = makeCommandMenu()
CasBtn = makeCascadeMenu()
ChkBtn = makeCheckButtonMenu()
RadBtn = makeRadiobuttonMenu()
NoMenu = makeDisabledMenu()
mBar.tk_menuBar(CmdBtn, CasBtn, ChkBtn, RadBtn, NoMenu)
However I receive the following error:
Traceback (most recent call last):
File "Menu.py", line 106, in <module>
mBar.tk_menuBar(CmdBtn, CasBtn, ChkBtn, RadBtn, NoMenu)
AttributeError: 'Frame' object has no attribute 'tk_menuBar'
I read this post:
https://stackoverflow.com/questions/52015321/is-there-any-differences-between-python2-and-python3-about-adding-menu-bar-to-fr
And they say this attribute 'tk_menuBar' has been deprecated from both Python 2 and Python 3. Does anyone have a solution how it should be used in my version of python? (3.6).

mBar = Frame(root, relief=RAISED, borderwidth=2)
after loading the root Tk, you declared mBar as a variable for frame then you try to access it using Object oriented method which i think it won't work

You can still do the following
if name == "main":
root = Tk()
mBar = Frame(root, relief=RAISED, borderwidth=2)
mBar.pack(fill=X)
cmdBtn = makeCommandMenu()
casBtn = makeCascadeMenu()
chkBtn = makeCheckbuttonMenu()
radBtn = makeRadiobuttonMenu()
noMenu = makeDisabledMenu()
menuBar = Menu()
menuBar.add_cascade(label="command", menu=cmdBtn)
menuBar.add_cascade(label="cascade", menu=casBtn)
menuBar.add_cascade(label="check", menu=chkBtn)
menuBar.add_cascade(label="radio", menu=radBtn)
menuBar.add_cascade(label="disable",menu=noMenu)
root.mainloop()

Related

how do i use tkinter to open a new script, then when closing the new window return to the first script?

these two scripts worked fine seperatly and after many differant approches i have got the page1 to open menu_func however when i close menu_func the window remains but deletes the photos etc?
i want the back command to return to the page1 script
i also get this error,
invalid command name "36335088time_now"
while executing
"36335088time_now"
("after" script)
not related to my actual problem but if anybody knows how to get rid of it help would be appreciated
1.page1 code
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from time import strftime
import subprocess
import menu_func
page1 = tk.Toplevel()
width_value=page1.winfo_screenwidth()
height_value=page1.winfo_screenheight()
page1.geometry('%dx%d-0+0' % (width_value, height_value))
page1.resizable(False, False)
BG1_img = Image.open('BG-BLK-1.png')
BG2_img = BG1_img.resize((width_value,height_value))
BG3_img = ImageTk.PhotoImage(BG2_img)
canvas = Canvas(page1)
canvas.pack(expand=True, fill=tk.BOTH)
limg = Label(canvas, i=BG3_img)
limg.pack()
SD1_img = Image.open('Bshut.png')
SD2_img = ImageTk.PhotoImage(SD1_img)
MU1_img = Image.open('./LIST.png')
MU2_img = ImageTk.PhotoImage(MU1_img)
def close():
page1.destroy()
#def MU_COMM():
# import menu_func.py
# page1.exit()
# exec(open('menu_func.py').read())
def time_now():
T_D = strftime('%A, %d %h %Y %H:%M:%S')
show_date.config(text = T_D)
show_date.after(1000, time_now)
exit_button = Button(canvas,image=SD2_img,
command=close,borderwidth='0',border='0',bg='#000000', highlightthickness='0')
exit_button.place(x=1700, y=900)
show_date = Label(canvas, font="Calibri, 46", fg="red", border='0',bg='#00090e')
show_date.place(x=440, y=960)
menu_button = Button(canvas, image=MU2_img, command= menu_func.menu, borderwidth=0,
bg='#000000', highlightthickness=0)
menu_button.place(x=50, y=900)
time_now()
page1.wm_attributes('-fullscreen', 'True')
page1.mainloop()
2.menu_func code
import tkinter as tk
from tkinter import *
from tkinter.messagebox import showinfo
from PIL import Image, ImageTk
from time import strftime
def menu():
pageM = tk.Toplevel()
w_v=pageM.winfo_screenwidth()
h_v=pageM.winfo_screenheight()
pageM.geometry('%dx%d-0+0' % (w_v, h_v))
pageM.resizable(False, False)
BG1m_img = Image.open('BG-BLK-1.png')
BG2m_img = BG1m_img.resize((w_v,h_v))
BG3m_img = ImageTk.PhotoImage(BG2m_img)
canvas = Canvas(pageM)
butt_W = int(w_v/28)
butt_H = int(h_v/31)
img_W = int(w_v/8)
img_H = int(h_v/4)
canvas = Canvas(pageM)
canvas.pack(expand=True, fill=tk.BOTH)
limg = Label(canvas, i=BG3m_img)
limg.pack()
def time_now():
T_D = strftime('%H:%M:%S')
show_time.config(text = T_D)
show_time.after(1000, time_now)
show_time = Label(canvas, font="Calibri, 46", fg="red", border='0',bg='#003a52')
show_time.place(x=int(w_v/2.3), y=int(h_v/50))
def call_COM():
showinfo(title='Information',message='phone Button clicked!')
call_img = Image.open('CALL.png')
cal1_img = call_img.resize((img_W,img_H))
cal2_img = ImageTk.PhotoImage(cal1_img)
button1=tk.Button(canvas, image=(cal2_img),borderwidth=0,bg='#000000', highlightthickness=0)
button1.place(x=int(w_v/5*1-(img_W)+50),y=int(h_v/3*0.8-(img_H/2)))
def map_COM():
exec(open("mapscreen.py").read())
c1_img = Image.open('comp.png')
c2_img = c1_img.resize((img_W,img_H))
c3_img = ImageTk.PhotoImage(c2_img)
button2=tk.Button(canvas, image=c3_img,command=map_COM,borderwidth=0,bg='#000000', highlightthickness=0)
button2.place(x=int(w_v/5*2-(img_W/1.2)+50),y=int(h_v/3*0.8-(img_H/2)))
def user_COM():
showinfo(title='Information',message='user Button clicked!')
u1_img = Image.open('user.png')
u2_img = u1_img.resize((img_W,img_H))
u3_img = ImageTk.PhotoImage(u2_img)
button3=tk.Button(canvas, image=u3_img,borderwidth=0,bg='#000000', highlightthickness=0)
button3.place(x=int(w_v/5*3-(img_W/1.5)+50),y=int(h_v/3*0.8-(img_H/2)))
def set_COM():
showinfo(title='Information',message='settings Button clicked!')
s1_img = Image.open('settings.png')
s2_img = s1_img.resize((img_W,img_H))
s3_img = ImageTk.PhotoImage(s2_img)
button4=tk.Button(canvas, image=s3_img,borderwidth=0,bg='#000000', highlightthickness=0)
button4.place(x=int(w_v/5*4-(img_W/2)+50),y=int(h_v/3*0.8-(img_H/2)))
def bro_COM():
exec(open('browser.py').read())
b1_img = Image.open('brows.png')
b2_img = b1_img.resize((img_W,img_H))
b3_img = ImageTk.PhotoImage(b2_img)
button5=tk.Button(canvas, image=b3_img,command=bro_COM,borderwidth=0,bg='#000000', highlightthickness=0)
button5.place(x=int(w_v/5*1-(img_W)+50),y=int(h_v/3*2.2-(img_H/1.5)))
def mus_COM():
showinfo(title='Information',message='Music Button clicked!')
m1_img = Image.open('music.png')
m2_img = m1_img.resize((img_W,img_H))
m3_img = ImageTk.PhotoImage(m2_img)
button6=tk.Button(canvas, image=m3_img,borderwidth=0,bg='#000000', highlightthickness=0)
button6.place(x=int(w_v/5*2-(img_W/1.2)+50),y=int(h_v/3*2.2-(img_H/1.5)))
def lite_COMM():
showinfo(title='Information',message='hardware Button clicked!')
t1_img = Image.open('Torch.png')
t2_img = t1_img.resize((img_W,img_H))
t3_img = ImageTk.PhotoImage(t2_img)
button7=tk.Button(canvas, image=t3_img,borderwidth=0,bg='#000000', highlightthickness=0)
button7.place(x=int(w_v/5*3-(img_W/1.5)+50),y=int(h_v/3*2.2-(img_H/1.5)))
def back_COM():
pageM.quit()
# exec(open('start_screen.py').read())
SD1_img = Image.open('home.png')
SD2_img = SD1_img.resize((img_W,img_H))
SD3_img = ImageTk.PhotoImage(SD2_img)
button8=tk.Button(canvas, image=SD3_img,command=back_COM,borderwidth=0,bg='#000000', highlightthickness=0)
button8.place(x=int(w_v/5*4-(img_W/2)+50),y=int(h_v/3*2.2-(img_H/1.5)))
time_now()
print(w_v/5*4-(img_W/2))
print(w_v/5*1-(img_W))
print(img_W)
print(h_v)
print(w_v)
pageM.mainloop()
the print(variables) arnt really part of the script there just there to help me work out locations of widgets!
i also understand this is a long code, if anybody know a way to make it shorter or more efficient please let me know, im not a programmer
thanks

TypeError: Menus.__init__() takes 1 positional argument but 2 were given

I'm shucked at his error TypeError: Menus.__init__() takes 1 positional argument but 2 were given any one please help me to solve his error
main file: -->
from tkinter import *
from meanu_items import *
def main():
windows = Tk()
windows.title("NotePad")
windows.minsize(width=60, height=80)
windows.config()
# Create place to write a text
text = Text(windows)
text.focus()
text.grid(pady=0.5, padx=10)
# Creating Scale
scroll = Scrollbar(windows, orient=VERTICAL, )
scroll.grid(row=0, column=1, sticky=NS + SE)
text.config(yscrollcommand=scroll.set)
scroll.config(command=text.yview)
menu = Menus(windows)
windows.mainloop()
if __name__ == '__main__':
main()
meanu_items file: -->
from tkinter import *
from tkinter import filedialog
SIDE_R = RIGHT
class Menus(Frame):
def __init__(self):
Frame.__init__()
self.filetypes = (
('text files', '*.txt'),
('All files', '*.*'))
self.text = Text()
self.menubar()
def menubar(self):
# Menu bar
# # File
menubar = Menu(self)
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open", command=self.opens)
file.add_command(label="Save")
file.add_command(label="close")
file.add_separator()
file.add_command(label="Exit", command=self.quit)
menubar.add_cascade(label="File", menu=file)
# # Edit
edit = Menu(menubar, tearoff=0)
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Cute")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=edit)
# # Help
helps = Menu(menubar, tearoff=0)
helps.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
def opens(self):
dlg = filedialog.Open(self, filetypes=self.filetypes)
fl = dlg.show()
if fl != '':
text = self.readFile(fl)
self.text.insert(END, text)
some minor error are also there in above file(meanU_items):-->
Expected type 'Menu', got '(args: tuple[Any, ...], kwds: dict[str, Any]) -> None' instead : 50
Unresolved attribute reference 'readFile' for class 'Menus' :57
Its difficult to tell, but perhaps you meant to pass in the windows parameter to pass it onto the Frame super class:
class Menus(Frame):
def __init__(self, windows):
super().__init__(windows)
...
Menu class is asking 'self'
class Menus(Frame):
def __init__(self):
but instead of a Menus object you gave it a window object. Write this in init:
class Menus(Frame):
def __init__(self, windows):
and create Menus object like this:-
menu = Menus(menus_items.Menus, windows)

PYTHON Attribute Error while running this GUI

So, I'm following a tutorial on making a simple calculator, and I'm Getting an attribute error AttributeError:'_tkinter.tkapp' object has no attribute 'displayframe' , apparently, the attribute doesn't exist in the source code even if it has been defined? would be grateful if someone helped
from tkinter import *
SMALL_FONT_STYLE = "Arial 16"
LIGHT_GRAY = "#F5F5F5"
LABEL_COLOR = "#25265E"
LARGE_FONT_STYLE = "Arial 40 bold"
WHITE = "#FFFFFF"
class Calculator(Tk):
def __init__(self):
super().__init__()
self.geometry("375x677")
self.resizable(0,0)
self.title("Calculator")
self.total_expression = "0"
self.current_expression = "0"
self.total_label, self.label = self.create_display_labels()
self.digits = {7:(1,1), 8:(1,2), 9:(1,3), 4:(2,1), 5:(2,2), 6:(2,3), 1:(3,1),2:(3,2), 3:(3,3), 0:(4,2), '.':(4,1)}
self.create_digits_buttons()
self.display_frame = self.create_display_frame()
self.buttons_frame = self.create_buttons_frame()
def create_display_labels(self):
total_label = Label(self.display_frame, text=self.total_expression, anchor=E, bg=LIGHT_GRAY, fg=LABEL_COLOR, padx=24, font=SMALL_FONT_STYLE)
total_label.pack(expand=True, fill="both")
label = Label(self.display_frame, text=self.total_expression, anchor=E, bg=LIGHT_GRAY, fg=LABEL_COLOR, padx=24, font=LARGE_FONT_STYLE)
label.pack(expand=True, fill="both")
return total_label, label
def create_display_frame(self):
frame = Frame(self, height=221, bg=LIGHT_GRAY)
frame.pack(expand=True, fill="both")
return frame
def create_buttons_frame(self):
frame = Frame(self)
frame.pack(expand=TRUE, fill="both")
return frame
def create_digits_buttons(self):
for digit, grid_value in self.digits.items():
button = Button(self.buttons_frame, text= str(digit), bg=WHITE, fg=LABEL_COLOR)
button.grid(row = grid_value[0], column = grid_value[1], sticky=NSEW)
if __name__ == '__main__':
Calc = Calculator()
Calc.mainloop()```
This error is because you call self.create_display_labels() before calling self.create_display_frame(). You also call self.create_digits_buttons() before calling self.create_buttons_frame().
Move self.create_display_labels() and self.create_digits_buttons() below self.create_display_frame() and self.create_buttons_frame(). Here is what __init__() should look like:
def __init__(self):
super().__init__()
self.geometry("375x677")
self.resizable(0,0)
self.title("Calculator")
self.total_expression = "0"
self.current_expression = "0"
self.digits = {7:(1,1), 8:(1,2), 9:(1,3), 4:(2,1), 5:(2,2), 6:(2,3), 1:(3,1),2:(3,2), 3:(3,3), 0:(4,2), '.':(4,1)}
self.display_frame = self.create_display_frame()
self.buttons_frame = self.create_buttons_frame()
self.create_digits_buttons() ### MOVED THIS LINE
self.total_label, self.label = self.create_display_labels() ### MOVED THIS LINE

python AttributeError: NoneType has no attribute

In my program snippet I create a python window with 2 fields and 3 buttons. The left two buttons should perform some action but instead an error is thrown:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib64/python3.4/tkinter/__init__.py", line 1538, in __call__
return self.func(*args)
File ".../GuiFile.py", line 11, in <lambda>
self.F[2] = ButtonClass().make_button(stacked="left",buttontext= "Action button", buttoncommand = lambda: cf.mainButtons.doButtonAction1(self))
File ".../ClassFile.py", line 11, in doButtonAction1
print(gf.StartGui.F[0].textField.get("1.0","end-1c"))
AttributeError: 'NoneType' object has no attribute 'textField'
Why is dict item F[0] (created in line 9 of GuiFile.py) not recognized as Text() class with the attribute textField (defined in line 43 of GuiFile.py)?
MainProgramFile.py
#!/usr/bin/env python3
import sys
import ClassFile
import GuiFile as gf
if __name__== '__main__':
gf.StartGui().mainloop()
GuiFile.py
import sys
from tkinter import *
import ClassFile as cf
class StartGui(Frame):
F = {}
def __init__(self,parent=None):
Frame.__init__(self, parent)
self.F[0] = FieldTextClass().make_field(labeltext="Label of field 1", fieldtext="veld 1", fieldheight=90)
self.F[1] = FieldTextClass().make_field(labeltext="Label of field 2", fieldtext="veld 2")
self.F[2] = ButtonClass().make_button(stacked="left",buttontext= "Action button", buttoncommand = lambda: cf.mainButtons.doButtonAction1(self))
self.F[3] = ButtonClass().make_button(stacked="left", buttontext= "Exchange button", buttoncommand = lambda: cf.mainButtons.doButtonSwitchValues(self))
self.F[4] = ButtonClass().make_button(stacked="right",buttontext= "Quit button",buttoncommand = lambda: cf.mainButtons.doButtonQuit(self))
self.pack(expand=True, fill=BOTH, anchor="nw", side=LEFT)
#for i in range(self.F.__len__()): print(self.F[i].__class__,self.F[i].objectType)
class ButtonClass (Frame, Button):
objectType = "button"
def make_button(self, parent=None, stacked="horizontal", buttontext="Button", buttonwidth=120, buttonheight=32, buttoncommand=""):
self.buttonwidth=buttonwidth
self.buttonheight=buttonheight
self.buttontext=buttontext
self.buttoncommand=buttoncommand
if stacked=="vertical":
BUTTONSTACK = TOP
elif stacked=="right":
BUTTONSTACK = RIGHT
elif stacked=="horizontal" or stacked=="left":
BUTTONSTACK = LEFT
else:
BUTTONSTACK = LEFT
self.top = Frame(parent, height=self.buttonheight, width=self.buttonwidth)
self.top.pack_propagate(False)
self.top.pack(side=BUTTONSTACK)
button = Button(self.top, text=self.buttontext, command=self.buttoncommand,height=self.buttonheight, width=self.buttonwidth)
button.pack(fill=BOTH)
class FieldTextClass(Frame,Text,Label):
textField = None
objectType = "inputField"
def make_field(self, parent=None, labeltext="Empty", fieldtext="Empty", fieldwidth=600, fieldheight=20, labelwidth=120, labelheight=20):
self.fieldheight=fieldheight
self.fieldwidth=fieldwidth
self.fieldtext=fieldtext
self.labeltext=labeltext
self.labelheight=labelheight
self.labelwidth=labelwidth
self.top = Frame(parent)
#create the label, whith the text shifted left/top in a separate Frame
labelFrame = Frame(self.top, height = self.labelheight,width=self.labelwidth)
label = Label(labelFrame, text=self.labeltext, fg="black", anchor="nw")
label.pack(expand=True, fill=BOTH, anchor="nw", side=LEFT)
labelFrame.pack_propagate(False)
labelFrame.pack(side=LEFT, anchor="nw")
#create the text field, packed in a separate Frame
fieldFrame = Frame(self.top, height = self.fieldheight,width=self.fieldwidth)
self.textField = Text(fieldFrame, fg="black",bg="white")
self.textField.insert(INSERT,self.fieldtext)
self.textField.pack(expand=True, fill=BOTH, side=LEFT)
fieldFrame.pack_propagate(False)
fieldFrame.pack(side=LEFT)
self.top.pack(side=TOP)
ClassFile.py
import sys
from tkinter import *
import GuiFile as gf
class mainButtons():
def doButtonQuit(self):
print("Quitting test via ClassFile")
self.quit()
def doButtonAction1(self):
print(gf.StartGui.F[0].textField.get("1.0","end-1c"))
print(gf.StartGui.F[1].textField.get("1.0","end-1c"))
gf.StartGui.F[0].textField.delete("1.0","end")
gf.StartGui.F[0].textField.insert(INSERT, "New text")
def doButtonSwitchValues(self):
tmp0=gf.StartGui.F[0].textField.get("1.0","end-1c")
tmp1=gf.StartGui.F[1].textField.get("1.0","end-1c")
gf.StartGui.F[0].textField.delete("1.0","end")
gf.StartGui.F[0].textField.insert(INSERT, tmp1)
gf.StartGui.F[1].textField.delete("1.0","end")
gf.StartGui.F[1].textField.insert(INSERT, tmp0)
When you do ButtonClass().make_button() (or FieldTextClass.make_field()) , python will return the value of the function, not the instance of the class. The function returns None, so the dictionary elements are None.
The way you're using the custom classes is very strange. Instead of creating special functions, put that code in an __init__, and use the class like you would any other class.
For example:
class ButtonClass (Frame):
def __init__(self, parent=None, stacked="horizontal",
buttontext="Button", buttonwidth=120, buttonheight=32,
buttoncommand=""):
Frame.__init__(self, parent)
self.buttonwidth=buttonwidth
...
...
self.F[2] = ButtonClass(stacked="left",buttontext= "Action button", buttoncommand = lambda: cf.mainButtons.doButtonAction1(self))
Note: when doing it this way, you don't have to create a separate frame inside __init__ (ie: self.top), since self is itself already a Frame.

Keep getting a certain error with tkinter root.destroy

I have been having lots of problems with this code, it is giving me a weird error. It occurs when I attempt to close the program; I get this error(shown at the bottom ). I also previously before adding the .protocol but was getting an error to do with the module. Is it the way I have imported tkinter? Or what I am attempting to destroy?
import tkinter.ttk
from tkinter.constants import *
from tkinter import *
class App(ttk.Frame):
#classmethod
def main(cls):
GUI = tkinter.Tk()
app = cls(GUI)
app.grid(sticky=NSEW)
GUI.grid_columnconfigure(0, weight=1)
GUI.grid_rowconfigure(0, weight=1)
GUI.resizable(True, False)
GUI.mainloop()
self.protocol("WM_DELETE_WINDOW", self.destroy())
GUI.protocol("WM_DELETE_WINDOW", GUI.destroy())
def __init__(self, GUI):
super().__init__(GUI)
self.create_variables()
self.create_widgets()
self.grid_widgets()
self.grid_columnconfigure(0, weight=1)
def create_variables(self):
pass
def create_widgets(self):
self.Logo = tkinter.PhotoImage(file="Logo.gif")
self.x = Label(image=self.Logo)
##Top bar Widgets##
self.button1 =ttk.Button(self, text="Profile", command=self.GetProfile)
if self.CheckLogin() == False:
self.button2 = ttk.Button(self, text="Log in", command=self.Login)
self.button3 = ttk.Button(self, text="Download",command=self.download)
self.Label2 = ttk.Label(self,text="")
def grid_widgets(self):
options = dict(sticky=NSEW, padx=3, pady=4)
options1 = dict(sticky=N)
self.x.grid(column=0,row=1, **options1)
#top bar
self.button1.grid(column = 1,row = 1,**options1)
self.button2.grid(column = 2,row = 1,**options1)
self.button3.grid(column = 3,row = 1,**options1)
#To be completed functions
def download(self):
pass
def GetProfile(self):
pass
def Login(self):
if self.Logindefault() == True:
print("login here")
elif self.Logindefault() == False:
self.v = StringVar()
print("Not logged in.")
options = dict(sticky=NSEW, padx=3, pady=4)
self.t = Toplevel(self)
self.t.title("Login")
self.t.grid_columnconfigure(0, weight=1)
self.t.grid_rowconfigure(0, weight=1)
self.t.entry1 = ttk.Entry(self.t)
self.t.entry2 = ttk.Entry(self.t)
self.t.button1 = ttk.Button(self.t,text="login",command=self.destroy)
self.t.entry1.grid(column = 0 ,row = 0, **options)
self.t.entry1.insert(0,"Username")
self.t.entry2.grid(column = 0 ,row = 1, **options)
self.t.entry2.insert(0,"Password")
self.t.button1.grid(column = 1,row = 0,rowspan=2, **options)
self.t.checkbox = ttk.Checkbutton(self.t,text="Remember me",variable=self.v)
self.t.checkbox.grid(column =0,row=2,**options)
def destroy(self):
self.usernameGO = self.t.entry1.get()
self.passwordGO = self.t.entry2.get()
print(self.usernameGO,self.passwordGO,self.v)
self.t.destroy()
def CheckLogin(self):
return False #If not logged in.
def Logindefault(self):
try:
file = open("UserLog.txt","rt")
for i in file:
if i[0:6] =="__usr__":
self.username = i.sptrip("__usr__")
elif i[0:6] =="__pss__":
self.password = i.strip("__pss__")
return True
except Exception:
#username file not found
print("error")
return False
if __name__ == '__main__':
App.main()
Here is the error which I get when I try to close the main window:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:\Python34\lib\tkinter\__init__.py", line 1892, in destroy
for c in list(self.children.values()): c.destroy()
File "C:\Users\charlie\Desktop\Yahtzee - Copy.py", line 74, in destroy
self.usernameGO = self.t.entry1.get()
AttributeError: 'App' object has no attribute 't'
self.protocol("WM_DELETE_WINDOW", self.destroy())
GUI.protocol("WM_DELETE_WINDOW", GUI.destroy())
Generally, when you register callback methods, you need to omit the parentheses. Otherwise, the methods will be called immediately, and their return values will be registered instead. This means that destroy will be executed before Login executes, so self.t won't yet exist. Try:
self.protocol("WM_DELETE_WINDOW", self.destroy)
GUI.protocol("WM_DELETE_WINDOW", GUI.destroy)

Categories

Resources