Attribute Error: '_tkinter.tkapp' object has no attribute 'root' - python

I don’t understand why this error appears, I have two source codes in one, everything works fine, in the second this error comes out. Looked at similar questions
but it did not give a result
try:
from Tkinter import * # for Python2
except ImportError:
from tkinter import * # for Python3
class Application(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.initialize_user_interface()
def initialize_user_interface(self):
self.master.root.title("Работа с планом")
self.master.root.geometry('400x300+200+200')
self.lbl_name = Label(root, text='Название проекта:', font=("Arial Bold", 14))
self.lbl_name.grid(column=0, row=1)
self.txt_name = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_name.grid(column=1, row=1)
self.lbl_lic = Label(root, text='Жидкость для работы:')
self.lbl_lic.grid(column=0, row=2)
self.txt_lic = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_lic.grid(column=1, row=2)
self.lbl_tank = Label(root, text='Имя танкера для работы:')
self.lbl_tank.grid(column=0, row=3)
self.txt_tank = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_tank.grid(column=1, row=3)
self.lbl_desk = Label(root, text='Описание действий сотрудника:')
self.lbl_desk.grid(column=0, row=4)
self.txt_desk = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_desk.grid(column=1, row=4)
self.lbl_agr = Label(root, text='Согласование работ с нормоконтролером:')
self.lbl_agr.grid(column=0, row=5)
self.txt_agr = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_agr.grid(column=1, row=5)
self.txt_name.focus()
self.but_b = Button(root, text="Назад", font=("Arial Bold", 14))
self.but_b.grid(column=0, row=6)
self.but_go = Button(root, text="Вперед", font=("Arial Bold", 14), command=self.safe)
self.but_go.grid(column=0, row=7)
self.but_safe = Button(root, text="Сохранить", font=("Arial Bold", 14))
self.but_safe.grid(column=1, row=6)
self.but_del = Button(root, text="Удалить", font=("Arial Bold", 14))
self.but_del.grid(column=1, row=7)
if __name__ == '__main__':
root = tk.Tk()
run = Application(root)
Application(root)
root.mainloop()

Firstly, when you are changing the Root Title and geometry, you do not need to call the root simply leaving it as self.master.geometry('400x300+200+200') will work fine.
Secondly, when using from tkinter import * you do not need to use tk.Frame you can just use Frame as Python will recognise this as a class name.
Thirdly one of your button commands self.safe will cause an error because this method is not defined nor is it a built in Tk command.
Improved code...
from tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.master = master
self.initialize_user_interface()
def initialize_user_interface(self):
self.master.title("Работа с планом")
self.master.geometry('400x300+200+200')
self.lbl_name = Label(root, text='Название проекта:', font=("Arial Bold", 14))
self.lbl_name.grid(column=0, row=1)
self.txt_name = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_name.grid(column=1, row=1)
self.lbl_lic = Label(root, text='Жидкость для работы:')
self.lbl_lic.grid(column=0, row=2)
self.txt_lic = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_lic.grid(column=1, row=2)
self.lbl_tank = Label(root, text='Имя танкера для работы:')
self.lbl_tank.grid(column=0, row=3)
self.txt_tank = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_tank.grid(column=1, row=3)
self.lbl_desk = Label(root, text='Описание действий сотрудника:')
self.lbl_desk.grid(column=0, row=4)
self.txt_desk = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_desk.grid(column=1, row=4)
self.lbl_agr = Label(root, text='Согласование работ с нормоконтролером:')
self.lbl_agr.grid(column=0, row=5)
self.txt_agr = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_agr.grid(column=1, row=5)
self.txt_name.focus()
self.but_b = Button(root, text="Назад", font=("Arial Bold", 14))
self.but_b.grid(column=0, row=6)
self.but_go = Button(root, text="Вперед", font=("Arial Bold", 14), command=None)
self.but_go.grid(column=0, row=7)
self.but_safe = Button(root, text="Сохранить", font=("Arial Bold", 14))
self.but_safe.grid(column=1, row=6)
self.but_del = Button(root, text="Удалить", font=("Arial Bold", 14))
self.but_del.grid(column=1, row=7)
if __name__ == '__main__':
root = Tk()
run = Application(root)
Application(root)
root.mainloop()

Related

Calling a variable from a def function to another def function

I'm having a hard time with calling the recordtable variable from my def btn3function() to my def update(). Anyone can help how I can call it without any error? Here's the full detail. I hope this will help, and thank you in advance again. I'm open to any suggestion or ideas. Willing to be enlightened.
reg = []
def register(name, number, date, time):
reg.append([name, number, date, time])
update()
def update(recordtable):
for item in recordtable.get_children():
recordtable.delete(item)
for r in range(len(reg)):
recordtable.insert(parent='', index='end', text='', iid=r, values=reg[r])
def btn3function(recordtable):
top = tkinter.Toplevel(root)
top.title("APPOINTMENTS")
frame = tk.Frame(top)
bg = ImageTk.PhotoImage(file="appointments.png")
labl = tk.Label(frame, image=bg)
labl.img = bg
labl.place(relx=0.5, rely=0.5, anchor='center')
frame.pack(pady=10)
frame.pack_propagate(False)
frame.configure(width=1000, height=790)
name = tk.Label(frame, text="Name:", font=('Bold', 16))
name.place(x=180, y=250)
nameEntry = tk.Entry(frame, font=('Bold', 16))
nameEntry.place(x=280, y=250, width=180)
number = tk.Label(frame, text="Number:", font=('Bold', 16))
number.place(x=180, y=300)
numberEntry = tk.Entry(frame, font=('Bold', 16))
numberEntry.place(x=280, y=300, width=180)
date = tk.Label(frame, text="Date:", font=('Bold', 16))
date.place(x=550, y=250)
dateEntry = tk.Entry(frame, font=('Bold', 16))
dateEntry.place(x=620, y=250, width=180)
time = tk.Label(frame, text="Time:", font=('Bold', 16))
time.place(x=550, y=300)
timeEntry = tk.Entry(frame, font=('Bold', 16))
timeEntry.place(x=620, y=300, width=180)
register = tk.Button(frame, text="Register", font=('Bold', 16))
register.place(x=270, y=380)
update = tk.Button(frame, text="Update", font=('Bold', 16))
update.place(x=400, y=380)
delete = tk.Button(frame, text="Delete", font=('Bold', 16))
delete.place(x=510, y=380)
clear = tk.Button(frame, text="Clear", font=('Bold', 16))
clear.place(x=620, y=380)
searchNum = tk.Label(frame, text="Search Appointment by Number:", font=('Bold', 14))
searchNum.place(x=210, y=450)
searchEntry = tk.Entry(frame, font=('Bold', 14))
searchEntry.place(x=500, y=450)
recordlabel = tk.Label(frame, text='Select Record to Update or Delete', bg='white', font=('Bold', 14))
recordlabel.pack(fill=tk.X)
recordlabel.place(x=350, y=500)
recordtable = ttk.Treeview(frame)
recordtable.pack(fill=tk.X, pady=5, side=BOTTOM)
recordtable['column'] = ['Name', 'Number', 'Date', 'Time']
recordtable.column('#0', anchor=tk.W, width=0, stretch=tk.NO)
recordtable.column('Name', anchor=tk.W, width=100)
recordtable.column('Number', anchor=tk.W, width=100)
recordtable.column('Date', anchor=tk.W, width=100)
recordtable.column('Time', anchor=tk.W, width=100)
recordtable.heading('Name', text="NAME", anchor=tk.W)
recordtable.heading('Number', text="NUMBER", anchor=tk.W)
recordtable.heading('Date', text="DATE", anchor=tk.W)
recordtable.heading('Time', text="TIME", anchor=tk.W)
Pass the recordtable variable into update as a parameter: def btn3function(rt). I'm not sure where you're actually calling update, but when you do you should do this: update(recordtable) somewhere after the declaration of recordtable

Thonny how to fix this stacked label

When I press OK to print out the answer multiple times, the answers just stack on each other but are not replaced by each other, how do I fix this bug?
from tkinter import *
from tkinter import messagebox
def main():
global window
window = Tk()
window.title("Calculator")
window.geometry("540x540")
label1 = Label(window, text="Calculator", font=("Windsor", 30), fg="light blue")
label1.pack()
global entry1
entry1 = Entry(window, width=20, font=("Arial 20"))
entry1.pack()
entry1.focus()
label2 = Label(window, text="+", font=("Windsor", 30), fg="light blue")
label2.pack()
global entry2
entry2 = Entry(window, width=20, font=("Arial 20"))
entry2.pack()
entry2.focus()
global label3
label3 = Label(window, text="=", font=("Windsor", 30), fg="light blue")
label3.pack()
button2 = Button(window, text="OK", fg="blue",
font="Arial 16 bold", command =button2_click)
button2.pack()
window.mainloop()
def button2_click():
Label.after(0, label.master.destroy)
try:
a = int(entry1.get())
b = int(entry2.get())
Label(window, text=f"{a+b}", font=("Windsor", 30), fg="light blue").pack()
except:
messagebox.showwarning("Error", "Invalid Entry or Entry Missing!")
if __name__=='__main__':
main()
It is better to create the result label once inside main() and update its text inside button2_click():
from tkinter import *
from tkinter import messagebox
def main():
global entry1, entry2, result
window = Tk()
window.title("Calculator")
window.geometry("540x540")
label1 = Label(window, text="Calculator", font=("Windsor", 30), fg="light blue")
label1.pack()
entry1 = Entry(window, width=20, font=("Arial 20"))
entry1.pack()
entry1.focus()
label2 = Label(window, text="+", font=("Windsor", 30), fg="light blue")
label2.pack()
entry2 = Entry(window, width=20, font=("Arial 20"))
entry2.pack()
label3 = Label(window, text="=", font=("Windsor", 30), fg="light blue")
label3.pack()
# create result label
result = Label(window, font=("Windsor", 30), fg="light blue")
result.pack()
button2 = Button(window, text="OK", fg="blue", font="Arial 16 bold", command=button2_click)
button2.pack()
window.mainloop()
def button2_click():
# below line will raise exception
#Label.after(0, label.master.destroy)
try:
a = int(entry1.get())
b = int(entry2.get())
# update result label
result.config(text=f"{a+b}")
except:
messagebox.showwarning("Error", "Invalid Entry or Entry Missing!")
if __name__=='__main__':
main()
Edit: I moved the button2_click () to the top. I comment out in line 17.
from tkinter import *
from tkinter import messagebox
window = Tk()
window = Tk()
def main():
global window
window.title("Calculator")
window.geometry("540x540")
label1 = Label(window, text="Calculator", font=("Windsor", 30), fg="light blue")
label1.pack()
def button2_click():
Label.after(0, label.master.destroy)
try:
a = int(entry1.get())
b = int(entry2.get())
Label(window, text=f"{a+b}", font=("Windsor", 30), fg="light blue").pack()
except:
messagebox.showwarning("Error", "Invalid Entry or Entry Missing!")
global entry1
entry1 = Entry(window, width=20, font=("Arial 20"))
entry1.pack(ipadx =10, ipady= 10)
entry1.focus()
label2 = Label(window, text="+", font=("Windsor", 30), fg="light blue")
label2.pack()
global entry2
entry2 = Entry(window, width=20, font=("Arial 20"))
entry2.pack()
entry2.focus()
global label3
label3 = Label(window, text="=", font=("Windsor", 30), fg="light blue")
label3.pack(ipadx =20, ipady= 20)
button2 = Button(window, text="OK", fg="blue",
font="Arial 16 bold", command =button2_click)
button2.pack()
window.mainloop()
def button2_click():
Label.after(0, label.master.destroy)
try:
a = int(entry1.get())
b = int(entry2.get())
Label(window, text=f"{a+b}", font=("Windsor", 30), fg="light blue").pack()
except:
messagebox.showwarning("Error", "Invalid Entry or Entry Missing!")
if __name__=='__main__':
main()

it seems like i can't open a frame in python

i want to open the menu_frame by clicking the login_button but the frame won't come up and there are no error messages showing up. its my first time and im so lost
ive tried to google how to fix this problem but from what ive read, it seems to me that there are no errors or any reason for this code to not function properly. please help :(
from tkinter import *
window = Tk()
window.title("EL TALLO")
window.geometry("700x490")
window.config(background="#FFF8E5")
#회원가입
def register_frame():
register_frame = Frame(
window,
bd=2,
bg='#FFF8E5',
relief=SOLID,
padx=10,
pady=10
)
Label(
register_frame,
text="ID입력",
bg='#CCCCCC',
).grid(row=0, column=0, sticky=W, pady=10)
Label(
register_frame,
text="비밀번호 입력",
bg='#CCCCCC',
).grid(row=5, column=0, sticky=W, pady=10)
newlyset_id = Entry(
register_frame
)
newlyset_pw = Entry(
register_frame,
show='*'
)
register_btn = Button(
register_frame,
width=15,
text='회원가입',
relief=SOLID,
cursor='hand2',
command=register_frame.destroy
)
newlyset_id.grid(row=0, column=1, pady=10, padx=20)
newlyset_pw.grid(row=5, column=1, pady=10, padx=20)
register_btn.grid(row=7, column=1, pady=10, padx=20)
register_frame.pack()
register_frame.place(x=220, y=150)
def new_id(): #new_id에 newlyset_id에 입력한 값을 저장
new_id = newlyset_id.get()
def new_pw(): #new_pw에 newlyset_pw에 입력한 값을 저장
new_pw = newlyset_pw.get()
#메뉴화면
def menu_frame():
menu_frame = Frame(
window,
bd=2,
bg='#FFF8E5',
relief=SOLID,
padx=10,
pady=10
)
label1 = Label(menu_frame, text = "EL TALLO", bg="lightgreen",width=10, height=1, font=(15))
label1.pack()
btn1 = Button(menu_frame, text = "play game", bg="gray", width=15, height=1)
btn1.pack()
btn2 = Button(menu_frame, text = "How to play", bg="gray", width=15, height=1)
btn2.pack()
btn3 = Button(menu_frame, text = "Settings", bg="gray", width=15, height=1)
btn3.pack()
def btncmd():
print("게임이 종료되었습니다")
btn4 = Button(menu_frame, text = "END GAME", command=btncmd, bg="lightgreen", width=15, height=1)
btn4.pack()
label1.place(x=50, y=50)
btn1.place(x=50, y=100)
btn2.place(x=50, y=150)
btn3.place(x=50, y=200)
btn4.place(x=50, y=250)
#로그인
Label(
window,
text="아이디 입력",
bg='#CCCCCC',
).place(x=230, y=170)
id_tf = Entry(
window,
).place(x=330, y=170)
def id(): #id에 id_tf에 입력한 값을 저장
id = id_tf.get()
Label(
window,
text="비밀번호 입력",
bg='#CCCCCC',
).place(x=230, y=220)
pw_tf = Entry(
window,
).place(x=330, y=220)
def pw(): #pw에 pw_tf에 입력한 값을 저장
pw = pw_tf.get()
#회원가입 버튼
registerbutton = Button(
window,
width=15,
text="회원가입",
bg="#CCCCCC",
cursor='hand2',
command=register_frame
)
registerbutton.place(x=360, y=270)
#로그인 버튼
loginbutton = Button(
window,
width=15,
text="로그인",
bg="#CCCCCC",
cursor='hand2',
command=menu_frame
)
loginbutton.place(x=230, y=270)
window.mainloop()
You didn't pack the menu_frame and the indentation of def btncmd() was wrong.
That is:
btn3 = Button(menu_frame, text = "Settings", bg="gray", width=15, height=1)
btn3.pack()
menu_frame.pack()
def btncmd():
print("게임이 종료되었습니다")

How to update Labels in tkinter?

I'm trying to create a program in where you put a word in a box, press add, and this word goes to a list, which is also displayed on the right side. When I press the forward button the first thing on the list is deleted. Problem is I can't get the labels to update when I press the buttons / edit the list.
from tkinter import *
root = Tk()
root.title('Speakers List')
root.minsize(800, 600)
speakers = ['none']
spe = speakers[0]
def add():
if spe == 'none':
speakers.insert(0, [s])
e.delete(0, END)
spe.config(text=speakers[0])
else:
speakers[-2] = [s]
e.delete(0, END)
spe.config(text=speakers[0])
return
def forward():
if len(speakers) is 0:
return
else:
del speakers[0]
spe.config(text=speakers[0])
return
entry = StringVar()
e = Entry(root, width=30, font=("Arial", 20), textvariable=entry)
e.grid(row=0, sticky=W)
s = e.get()
button1 = Button(root, padx=10, pady=10, bd=5, text='Add', fg='black', command=add)
button1.grid(row=0, column=1)
button2 = Button(root, padx=10, pady=10, bd=5, text='Next', fg='black', command=forward)
button2.grid(row=1, column=1)
n = Label(root, font=("Arial", 35), bd=2, text=spe)
n.grid(row=1, sticky=W)
listdisplay = Label(root, font=('Arial', 20), text=speakers)
listdisplay.grid(row=0, column=10)
root.mainloop()
Is this the sort of thing you were looking for ?
from tkinter import *
root = Tk()
root.title('Speakers List')
root.minsize(800, 600)
speakers = ['50']
spe = speakers[0]
def add():
entry=e.get()
speakers.append(entry)
listdisplay.config(text=speakers)
return
def forward():
if len(speakers) is 0:
return
else:
del speakers[0]
listdisplay.config(text=speakers)
spe=speakers[0]
n.config(text=spe)
return
entry = StringVar()
e = Entry(root, width=30, font=("Arial", 20), textvariable=entry)
e.grid(row=0, sticky=W)
s = e.get()
button1 = Button(root, padx=10, pady=10, bd=5, text='Add', fg='black',command=add)
button1.grid(row=0, column=1)
button2 = Button(root, padx=10, pady=10, bd=5, text='Next', fg='black',command=forward)
button2.grid(row=1, column=1)
n = Label(root, font=("Arial", 35), bd=2, text=spe)
n.grid(row=1, sticky=W)
listdisplay = Label(root, font=('Arial', 20), text=speakers)
listdisplay.grid(row=0, column=10)
root.mainloop()
If so:
You create a list and then you use the append function to add an item to it. The rest was pretty much right.

Python Tkinter Entry() Calculations

I am currently trying to build a GUI calculator using python with the help of tkinter. I have managed to set up all of my buttons and they interact with my entry() bar when I press the button (e,g: Press button 5 and 5 appears into the entry()).
The only thing left to do is actually perform the mathematical equations that appear in the entry(). For example, if I enter 5 + 5 * 2 into the entry bar, how would I make the answer appear into the entry() after it's updated? So basically all I'm asking is someone to help me make this happen!
I have provided the code below and a screenshot of the calculator. Also please don't report this as a duplicate or flag this question as a post, (I'm reasking this question because I got no help on my last one so please help a young python programmer out!). Also I'm asking you not to provide me with links because I've read every possible link on tkinter there is to read and still have no clue what I'm doing.
Here is my code:
import sys
from tkinter import *
from PIL import Image, ImageTk
#ACTIONS:
def clear():
#Action: Clears the entry().
txtDisplay.delete(0,END);
return;
def update_Entry(inputValue):
#Updates the entry when a button is pressed.
currentText = num1.get();
update = num1.set(currentText + inputValue);
#Parent Window.
root = Tk();
root.title('Calculator ++ [1.7.2]');
root.geometry('350x450');
#Main entry.
num1 = StringVar();
txtDisplay = Entry(root, textvariable = num1, relief=RIDGE, bd = 10, width=33, insertwidth = 1, font = 40, justify=RIGHT);
txtDisplay.place(x=15, y=10);
txtDisplay.focus();
print(txtDisplay.get())
#Buttons:
zeroButton = Button(root, text='0', width=20, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('0'));
zeroButton.place(x=17,y=382);
oneButton = Button(root, text='1', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('1'));
oneButton.place(x=17, y=302);
twoButton = Button(root, text='2', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('2'));
twoButton.place(x=100, y=302);
threeButton = Button(root, text='3', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('3'));
threeButton.place(x=182, y=302);
fourButton = Button(root, text='4', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('4'));
fourButton.place(x=17, y=222);
fiveButton = Button(root, text='5', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('5'));
fiveButton.place(x=100, y=222);
sixButton = Button(root, text='6', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('6'));
sixButton.place(x=182, y=222);
sevenButton = Button(root, text='7', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('7'));
sevenButton.place(x=17, y=142);
eightButton = Button(root, text='8', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('8'));
eightButton.place(x=100, y=142);
ninthButton = Button(root, text='9', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('9'));
ninthButton.place(x=182, y=142);
decimalButton = Button(root, text='.', width=8, height=3, bg='powder blue', command=lambda:update_Entry('.'));
decimalButton.place(x=182, y=382);
equalButton = Button(root, text='=', width=8, height=8, bg='Lightgreen', command=lambda:update_Entry('='));
equalButton.place(x=264, y=307);
plusButton = Button(root, text='+', width=8, height=3, bg='gray', command=lambda:update_Entry('+'));
plusButton.place(x=264, y=222);
minusButton = Button(root, text='-', width=8, height=3, bg='gray', command=lambda:update_Entry('-'));
minusButton.place(x=264, y=142);
multiplyButton = Button(root, text='x', width=8, height=3, bg='gray', command=lambda:update_Entry('*'));
multiplyButton.place(x=264, y=66);
divideButton = Button(root, text='÷', width=8, height=3, bg='gray', command=lambda:update_Entry('/'));
divideButton.place(x=182, y=66);
clearButton = Button(root, text='Clear (CE)', width=20, height=3, command = clear, bg='Orange');
clearButton.place(x=17, y=66);
#Locks the parent windows size.
root.maxsize(350,450);
root.minsize(350,450);
#Parent window's background color:
root.configure(background = 'black');
root.mainloop();
Screenshot:
For something this simple, try having this as the command for your equalButton:
def evaluate():
currentText = num1.get()
try:
num1.set(str(eval(currentText)))
except SyntaxError:
num1.set('<ERROR>')

Categories