Method requires self argument - python

I have this code right here, it's about a GUI app with Tkinter, pretty simple, but there is one error that I can't solve without breaking the code:
import tkinter as tk
class Sistema:
def __init__(self, g1 = 0, g2 = 0, g3 = 0, g4 = 0, media = 6):
self.g1 = g1
self.g2 = g2
self.g3 = g3
self.g4 = g4
self.media = media
resultCalc = (self.g1 + self.g2 + self.g3 + self.g4) / 4
self.resultCalc = resultCalc
Label_reply['text'] = Sistema.__str__()
def __str__(self):
if self.resultCalc < self.media:
return "Você não passou de ano! ╰(‵□′)╯"
elif self.resultCalc > self.media:
return "Você passou de ano!(~ ̄▽ ̄)~"
elif self.resultCalc == self.media:
return "Você passou de ano! Essa foi por pouco (。_。)"
else:
return "Erro fatal (╬▔皿▔)╯"
root = tk.Tk()
canvas = tk.Canvas(root, bg = "#159BA0", height = 500, width = 500)
canvas.pack()
Label1 = tk.Label(canvas, text = "Digite sua nota:")
Label1.place(x = 10,y = 10)
Entry1 = tk.Entry(canvas)
Entry1.place(x = 100,y = 10)
Label2 = tk.Label(canvas, text = "Digite sua nota:")
Label2.place(x = 10,y = 50)
Entry2 = tk.Entry(canvas)
Entry2.place(x = 100,y = 50)
Label3 = tk.Label(canvas, text = "Digite sua nota:")
Label3.place(x = 10, y = 90)
Entry3 = tk.Entry(canvas)
Entry3.place(x = 100, y = 90)
Label4 = tk.Label(canvas, text = "Digite sua nota:" )
Label4.place(x = 10, y = 130)
Entry4 = tk.Entry(canvas)
Entry4.place(x = 100, y = 130)
Label5 = tk.Label(canvas, text = "Média mínima: ")
Label5.place(x=10, y = 170)
Entry5 = tk.Entry(canvas)
Entry5.place(x=100, y = 170)
Button1 = tk.Button(canvas, text = "Enviar",
command = lambda : Sistema(float(Entry1.get()), float(Entry2.get()), float(Entry3.get()), float(Entry4.get()),
float(Entry5.get())))
Button1.place(x = 10, y = 210)
Label_reply = tk.Label(canvas)
Label_reply.place(x = 10, y = 240)
root.mainloop()
But, when I run it, it raises this exception:
TypeError: __str__() missing 1 required positional argument: 'self'
The error is at the 15 line.
I know what it means and why it happens, but I can't find a way to solve it without ruining the code, can someone help me?

Consider this line of code:
Label_reply['text'] = Sistema.__str__()
You are calling the __str__ method on the class rather than on an instance of the class. That is why it is asking for the self parameter.
I assume you want to call the __str__ method of the current object, which you can do by calling str(self):
Label_reply['text'] = str(self)

Delete this line:
Label_reply['text'] = Sistema.__str__()
This is an incorrect call to the __str__ function (it would need to be something more like str(self)), and it serves no purpose since there is no Label_reply within this scope anyway.
Instead, put the logic of updating Label_reply inside your command function:
Label_reply = tk.Label(canvas)
Label_reply.place(x = 10, y = 240)
def command():
s = Sistema(
float(Entry1.get()),
float(Entry2.get()),
float(Entry3.get()),
float(Entry4.get()),
float(Entry5.get())
)
Label_reply['text'] = str(s)
return s

Related

How to decrease the size of an entry in tkinter python

I want to decrease the size of an entry in tkinter python. ive already asked about label but i havent used fyi
the code:
from tkinter import *
from tkinter import messagebox
top = Tk()
top.title("Hello wold")
top.geometry("300x300")
ei = StringVar()
ei1 = StringVar()
def karma():
try:
ee = ei.get()
ee1 = ei1.get()
ez = int(ee) + int(ee1)
return messagebox.showinfo('message', f'{ee} + {ee1} = {ez}')
except ValueError:
return messagebox.showinfo('message', f'ERROR')
name = Label(top,text="1st no. : ").place(x = 20,y = 50)
e = Entry(top,textvariable=ei).place(x = 100, y = 50)
name1 = Label(top,text="2nd no. : ").place(x = 20,y = 100)
e1 = Entry(top,textvariable=ei1).place(x = 100, y = 100)
b = Button(top, text="Click here", command=karma).place(x = 20,y = 150)
top.mainloop()
you may use the font option in Entry to adjust the size.
Here is an example (to change it to 8pts)
import tkFont
helv8 = tkFont.Font(family='Helvetica', size=8)
e = Entry(top, font = helv8, textvariable=ei).place(x = 100, y = 50)

How can i run a whole sub class when the buttons are clicked which are in the main class

this is my first time trying subclasses, so I don't know if I did it right, but when I run this i get a few error
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
TypeError: cart_order() missing 1 required positional argument: 'self'
And
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\GGPC\OneDrive\Desktop\trying subclasses.py", line 337, in order_menu
t = final_cart(parent, Test)
NameError: name 'parent' is not defined.
and when i used command=t.calculate_order i got the error
self.button_checkout = Button(self.my_frame2, command = t.cart_order)
NameError: name 't' is not defined
Trying to run the sub class "final_cart" when the buttons are clicked that are in the main class. I did a lot of testing and trialing and could not find a solution, so your help is appreciated.
Thank you.
##importing all the models needed to create the program
from tkinter import*
from PIL import Image, ImageTk
import tkinter as ttk
import os
accounts = []
food = ['Pizza','Burger','Nachos', 'French Toast']
drinks = ['Pepsi','Lemonade','Tea', 'Aperitivo Spritz']
foodprice=['20','9.50','7.50', '17']
drinksprice = ['3','4','3', '15.50']
orderlist = []
class Goode_brothers:
def __init__(self, parent):
self.my_frame = Frame(parent)
self.my_frame.pack()
self.background = Image.open('new-dip-project\\food.jpg')
self.background_image = ImageTk.PhotoImage(self.background)
self.img = Label(parent, image = self.background_image)
self.img.place(x = -26, y =0)
self.img_login = PhotoImage(file = 'new-dip-project\\button (3).png')
self.login_button = Button(parent,image = self.img_login, command = self.read_info, bd = 0, cursor = "hand2", bg = '#3b353b', activebackground = '#3b353b')
self.login_button.place(x = 275, y = 340)
self.email = Entry(parent)
self.email.place(x = 340, y = 180)
self.password = Entry(parent, show = '●')
self.password.place(x = 354, y = 250)
def save_info(self):
self.email_reg = str(self.email2.get())
self.pass_word = str(self.password2.get())
print(self.email2)
file = open('emails.txt', 'a+')
file.write(self.email_reg + ', ' + self.pass_word + '\n')
def read_info(self):
with open("emails.txt") as read_ep:
for line in read_ep:
##appending the details in a list
accounts.append(line.strip().split(", "))
## getting what the user entered for email and password
credential = [self.email.get(), self.password.get()]
## if what the user entered is in the list then user can continue
if credential in accounts:
self.open_menu()
else:
## if the above conditions are not satisfied then user has th=o retry and this function will repeat until logged in
self.ep_notexist = Label(root, text = "Your Email or Password is incorrect, Please try again", font=("open sans", "8"))
self.ep_notexist.place(x = 210, y = 300)
self.ep_notexist.after(4000, self.ep_notexist.destroy)
self.email.delete(0, END)
self.password.delete(0, END)
## creating a function for home page
def open_menu(self):
for wid in root.winfo_children():
wid.destroy()
self.my_frame.destroy()
self.my_frame2 = Frame(root)
self.my_frame2.pack(fill = "both", expand = 1)
self.title_home = PhotoImage(file = 'new-dip-project\\goode.png')
self.title2 = Label(self.my_frame2, image = self.title_home).pack()
self.img_menu = PhotoImage(file = 'new-dip-project\\menu_button.png')
self.button_menu = Button(self.my_frame2,image = self.img_menu, command = self.view_menu, cursor = "hand2", bd = 0)
self.button_menu.place(x = 246, y = 140)
self.img_order = PhotoImage(file = 'new-dip-project\\order_button.png')
self.button_order = Button(self.my_frame2,image = self.img_order, command = self.order_menu, cursor = "hand2", bd = 0)
self.button_order.place(x = 239, y = 228)
self.img_checkout = PhotoImage(file = 'new-dip-project\\checkout.png')
self.button_checkout = Button(self.my_frame2,image = self.img_checkout, cursor = "hand2", bd = 0, command = final_cart.cart_order)
self.button_checkout.place(x = 250, y = 316)
def view_menu(self):
self.my_frame2.pack_forget()
self.my_frame3 = LabelFrame(root, height = 700)
self.my_frame3.pack()
self.my_frame3.columnconfigure(0, weight=1)
self.my_frame3.columnconfigure(1, weight=2)
self.food_title = Label(self.my_frame3, font=("Impact", "23"), text = 'Food').grid(row = 0, column = 4)
self.food_space = Label(self.my_frame3, text = '').grid(row = 1, column = 4)
self.drinks_title = Label(self.my_frame3, font=("Impact", "23"), text = 'Drinks').grid(row = 8, column = 4)
self.price = Label(self.my_frame3, font=("Impact", "23"), text = 'Price($)').grid(row = 0, column = 8)
for x in range (len(food)):
self.foodop = Label(self.my_frame3, font=("Impact", "15"), text = food[x]).grid(row = 3+x, column = 4)
self.fprice = Label(self.my_frame3, font=("Impact", "15"), text = foodprice[x]).grid(row = 3+x, column = 8)
for x in range (len(drinks)):
self.drinksop = Label(self.my_frame3, font=("Impact", "15"), text = drinks[x]).grid(row = 5+(len(food))+x, column = 4)
self.drinksp = Label(self.my_frame3, font=("Impact", "15"), text = drinksprice[x]).grid(row = 5+(len(food))+x, column = 8)
self.img_back = PhotoImage(file = 'new-dip-project\\back_button.png')
self.back_button = Button(self.my_frame3,image = self.img_back, command = self.open_menu, cursor = "hand2", bd = 0)
self.back_button.grid(row = 38, column = 7)
def order_menu(self):
self.my_frame2.destroy()
self.my_frame4 = Frame(root)
self.my_frame4.pack(fill = "both", expand = 1)
self.tkvar = StringVar(self.my_frame4)
self.tkvar.set("Food")
self.tkvar.trace_add('write', lambda *args: print(self.tkvar.get()))
self.tkvar2 = StringVar(self.my_frame4)
self.tkvar2.set("Drinks")
self.tkvar2.trace_add('write', lambda *args: print(self.tkvar2.get()))
self.img_odmenu = PhotoImage(file = 'new-dip-project\\od_menu.png')
self.order_menu_message = Label(self.my_frame4, image = self.img_odmenu).place(x = 220)
self.foodMenu = OptionMenu(self.my_frame4, self.tkvar, *['Pizza','Burger','Nachos', 'French Toast'])
self.foodMenu.place(x = 160, y = 110)
self.drinkMenu = OptionMenu(self.my_frame4, self.tkvar2, *['Pepsi','Lemonade','Tea', 'Aperitivo Spritz'])
self.drinkMenu.place(x = 385, y = 110)
self.order_btn1 = PhotoImage(file = 'new-dip-project\\orderb.png')
self.order_button2 = Button(self.my_frame4, text = "SHOW", image = self.order_btn1, command = t.calculate_order, cursor = "hand2", bd = 0)
self.order_button2.place(x = 302, y = 160)
self.check_btn = PhotoImage(file = 'new-dip-project\\checkpay.png')
self.checkout_btn = Button(self.my_frame4, image = self.check_btn, cursor = "hand2", bd = 0, command = t.cart_order)
self.checkout_btn.place(x = 267, y = 410)
self.img_back3 = PhotoImage(file = 'new-dip-project\\bbutton.png')
self.back_button3 = Button(self.my_frame4, image = self.img_back3, cursor = "hand2", bd = 0, command = self.open_menu)
self.back_button3.place(x = 50, y = 410)
t = final_cart(parent, Goode_brothers)
class final_cart(Goode_brothers):
def __init__(self, parent):
super(final_cart, self).__init__(self)
def cart_order(self):
self.root3 = Toplevel(root)
self.root3.geometry("600x400")
self.img_back2 = PhotoImage(file = 'new-dip-project\\bbutton.png')
self.back_button2 = Button(self.root3, image = self.img_back2, cursor = "hand2", bd = 0, command = self.open_menu)
self.back_button2.grid(column=0, row = 1)
self.img_cart = PhotoImage(file = 'new-dip-project\\your_cart.png')
self.y_cart = Label(self.root3, image = self.img_cart).grid(column=3, row = 1)
Label(self.root3, text = "",font=("Courier New","12")).grid(column = 1, row = 1)
Label(self.root3, text = "",font=("Courier New","12")).grid(column = 1, row = 4)
for x in range (len(orderlist)):
Label(self.root3, text = (str(x+1)),font=("Courier New","12")).grid(column =0, row= x+5)
Label(self.root3, text = (orderlist[x][0]), font=("Courier New","12")).grid(column=2, row = x+5)
def calculate_order(self):
print (orderlist)
def food_optionmenu(self, *args):
self.position = food.index(self.tkvar.get())
def drink_optionmenu(self, *args):
self.position2 = drinks.index(self.tkvar2.get())
self.tkvar.trace('w', self.food_optionmenu)
self.tkvar2.trace('w', self.drink_optionmenu)
## main routine
if __name__ == "__main__":
root = Tk()
root.geometry('670x466')
FoodSystem = Goode_brothers(root)
root.title('Goode brothers')
root.mainloop()
Ok, now I can see the route through your methods. They just need a clean up. I shall put some: ## comments in to show where I have changed something:
##importing all the models needed to create the program
from tkinter import*
from PIL import Image, ImageTk
import tkinter as ttk
import os
accounts = []
food = ['Pizza','Burger','Nachos', 'French Toast']
drinks = ['Pepsi','Lemonade','Tea', 'Aperitivo Spritz']
foodprice=['20','9.50','7.50', '17']
drinksprice = ['3','4','3', '15.50']
orderlist = []
class Goode_brothers:
def __init__(self, parent):
self.my_frame = Frame(parent)
self.my_frame.pack()
self.background = Image.open('new-dip-project\\food.jpg')
self.background_image = ImageTk.PhotoImage(self.background)
self.img = Label(parent, image = self.background_image)
self.img.place(x = -26, y =0)
self.img_login = PhotoImage(file = 'new-dip-project\\button (3).png')
self.login_button = Button(parent,image = self.img_login, command = self.read_info, bd = 0, cursor = "hand2", bg = '#3b353b', activebackground = '#3b353b')
self.login_button.place(x = 275, y = 340)
self.email = Entry(parent)
self.email.place(x = 340, y = 180)
self.password = Entry(parent, show = '●')
self.password.place(x = 354, y = 250)
def save_info(self):
self.email_reg = str(self.email2.get())
self.pass_word = str(self.password2.get())
print(self.email2)
file = open('emails.txt', 'a+')
file.write(self.email_reg + ', ' + self.pass_word + '\n')
def read_info(self):
with open("emails.txt") as read_ep:
for line in read_ep:
##appending the details in a list
accounts.append(line.strip().split(", "))
## getting what the user entered for email and password
credential = [self.email.get(), self.password.get()]
## if what the user entered is in the list then user can continue
if credential in accounts:
self.open_menu()
else:
## if the above conditions are not satisfied then user has th=o retry and this function will repeat until logged in
self.ep_notexist = Label(root, text = "Your Email or Password is incorrect, Please try again", font=("open sans", "8"))
self.ep_notexist.place(x = 210, y = 300)
self.ep_notexist.after(4000, self.ep_notexist.destroy)
self.email.delete(0, END)
self.password.delete(0, END)
## creating a function for home page
def open_menu(self):
for wid in root.winfo_children():
wid.destroy()
self.my_frame.destroy()
self.my_frame2 = Frame(root)
self.my_frame2.pack(fill = "both", expand = 1)
self.title_home = PhotoImage(file = 'new-dip-project\\goode.png')
self.title2 = Label(self.my_frame2, image = self.title_home).pack()
self.img_menu = PhotoImage(file = 'new-dip-project\\menu_button.png')
self.button_menu = Button(self.my_frame2,image = self.img_menu, command = self.view_menu, cursor = "hand2", bd = 0)
self.button_menu.place(x = 246, y = 140)
self.img_order = PhotoImage(file = 'new-dip-project\\order_button.png')
self.button_order = Button(self.my_frame2,image = self.img_order, command = self.order_menu, cursor = "hand2", bd = 0)
self.button_order.place(x = 239, y = 228)
self.img_checkout = PhotoImage(file = 'new-dip-project\\checkout.png')
self.button_checkout = Button(self.my_frame2,image = self.img_checkout, cursor = "hand2", bd = 0, command = self.cart_order) ## just self.cart_order
self.button_checkout.place(x = 250, y = 316)
def view_menu(self):
self.my_frame2.pack_forget()
self.my_frame3 = LabelFrame(root, height = 700)
self.my_frame3.pack()
self.my_frame3.columnconfigure(0, weight=1)
self.my_frame3.columnconfigure(1, weight=2)
self.food_title = Label(self.my_frame3, font=("Impact", "23"), text = 'Food').grid(row = 0, column = 4)
self.food_space = Label(self.my_frame3, text = '').grid(row = 1, column = 4)
self.drinks_title = Label(self.my_frame3, font=("Impact", "23"), text = 'Drinks').grid(row = 8, column = 4)
self.price = Label(self.my_frame3, font=("Impact", "23"), text = 'Price($)').grid(row = 0, column = 8)
for x in range (len(food)):
self.foodop = Label(self.my_frame3, font=("Impact", "15"), text = food[x]).grid(row = 3+x, column = 4)
self.fprice = Label(self.my_frame3, font=("Impact", "15"), text = foodprice[x]).grid(row = 3+x, column = 8)
for x in range (len(drinks)):
self.drinksop = Label(self.my_frame3, font=("Impact", "15"), text = drinks[x]).grid(row = 5+(len(food))+x, column = 4)
self.drinksp = Label(self.my_frame3, font=("Impact", "15"), text = drinksprice[x]).grid(row = 5+(len(food))+x, column = 8)
self.img_back = PhotoImage(file = 'new-dip-project\\back_button.png')
self.back_button = Button(self.my_frame3,image = self.img_back, command = self.open_menu, cursor = "hand2", bd = 0)
self.back_button.grid(row = 38, column = 7)
def order_menu(self):
self.my_frame2.destroy()
self.my_frame4 = Frame(root)
self.my_frame4.pack(fill = "both", expand = 1)
self.tkvar = StringVar(self.my_frame4)
self.tkvar.set("Food")
self.tkvar.trace_add('write', lambda *args: print(self.tkvar.get()))
self.tkvar2 = StringVar(self.my_frame4)
self.tkvar2.set("Drinks")
self.tkvar2.trace_add('write', lambda *args: print(self.tkvar2.get()))
self.img_odmenu = PhotoImage(file = 'new-dip-project\\od_menu.png')
self.order_menu_message = Label(self.my_frame4, image = self.img_odmenu).place(x = 220)
self.foodMenu = OptionMenu(self.my_frame4, self.tkvar, *['Pizza','Burger','Nachos', 'French Toast'])
self.foodMenu.place(x = 160, y = 110)
self.drinkMenu = OptionMenu(self.my_frame4, self.tkvar2, *['Pepsi','Lemonade','Tea', 'Aperitivo Spritz'])
self.drinkMenu.place(x = 385, y = 110)
self.order_btn1 = PhotoImage(file = 'new-dip-project\\orderb.png')
self.order_button2 = Button(self.my_frame4, text = "SHOW", image = self.order_btn1, command = self.calculate_order, cursor = "hand2", bd = 0) ## just self.calculate_order
self.order_button2.place(x = 302, y = 160)
self.check_btn = PhotoImage(file = 'new-dip-project\\checkpay.png')
self.checkout_btn = Button(self.my_frame4, image = self.check_btn, cursor = "hand2", bd = 0, command = self.cart_order) ## just self.cart_order
self.checkout_btn.place(x = 267, y = 410)
self.img_back3 = PhotoImage(file = 'new-dip-project\\bbutton.png')
self.back_button3 = Button(self.my_frame4, image = self.img_back3, cursor = "hand2", bd = 0, command = self.open_menu)
self.back_button3.place(x = 50, y = 410)
## You don't need this. An instance is created in main
##t = final_cart(parent, Goode_brothers)
class final_cart(Goode_brothers):
## No need for your own __init__, just inherit the one from Goode_brothers
def cart_order(self):
self.root3 = Toplevel(root)
self.root3.geometry("600x400")
self.img_back2 = PhotoImage(file = 'new-dip-project\\bbutton.png')
self.back_button2 = Button(self.root3, image = self.img_back2, cursor = "hand2", bd = 0, command = self.open_menu)
self.back_button2.grid(column=0, row = 1)
self.img_cart = PhotoImage(file = 'new-dip-project\\your_cart.png')
self.y_cart = Label(self.root3, image = self.img_cart).grid(column=3, row = 1)
Label(self.root3, text = "",font=("Courier New","12")).grid(column = 1, row = 1)
Label(self.root3, text = "",font=("Courier New","12")).grid(column = 1, row = 4)
for x in range (len(orderlist)):
Label(self.root3, text = (str(x+1)),font=("Courier New","12")).grid(column =0, row= x+5)
Label(self.root3, text = (orderlist[x][0]), font=("Courier New","12")).grid(column=2, row = x+5)
def calculate_order(self):
print (orderlist)
def food_optionmenu(self, *args):
self.position = food.index(self.tkvar.get())
def drink_optionmenu(self, *args):
self.position2 = drinks.index(self.tkvar2.get())
self.tkvar.trace('w', self.food_optionmenu)
self.tkvar2.trace('w', self.drink_optionmenu)
## main routine
if __name__ == "__main__":
root = Tk()
root.geometry('670x466')
FoodSystem = final_cart(root) ## Just make an instance of final_cart
root.title('Goode brothers')
root.mainloop()
Essentially you have subclassed Goode_brothers so the two classes act as one when you instantiate final_cart.
Firstly the line: class final_cart(Goode_brothers): means that final_cart inherits from Goode_brothers.
Secondly the line: FoodSystem = final_cart(root) instantiates final_cart making the two classes act as a single class. This means that any method which calls self.anothermethod() has access to the union of all the methods from the two classes.

i am trying to store some data into a text file, there are no errors but it writes ".!toplevel.!entrywrite" instead of user input

i am making a sign up page and im trying to store the email the user entered to a text file but it doesnt seem to work it stores ".!toplevel.!entrywrite" instead of user input. i am new to this python and tkinter so i dont really know what to do, the code is a little bit long sorry about that.
Any help will be appreciated. Thank you
from tkinter import*
from PIL import Image, ImageTk
import tkinter as tk
root = Tk()
root.geometry('670x466')
class Goode_brothers:
def __init__(self, parent):
myFrame = Frame(parent)
myFrame.pack()
self.load = Image.open('new-dip-project\\food.jpg')
self.render = ImageTk.PhotoImage(self.load)
self.img = Label(parent, image = self.render)
self.img.place(x = -26, y =0)
self.img_login = PhotoImage(file = 'new-dip-project\\button (3).png')
self.b1 = Button(parent,image = self.img_login,bd = 0, bg = '#3b353b', activebackground = '#3b353b')
self.b1.place(x = 275, y = 310)
self.img_register = PhotoImage(file = 'new-dip-project\\register.png')
self.b2 = Button(parent,image = self.img_register, command = self.openNewWindow, bd = 0, bg = '#3b353b', activebackground = '#3b353b')
self.b2.place(x = 265, y = 400)
self.canvas = Canvas(parent, width = 400, height = 120)
self.canvas.pack()
self.img4 = ImageTk.PhotoImage(Image.open('new-dip-project\\goode.png'))
self.canvas.create_image(20, 20, anchor=NW, image=self.img4)
self.email = Entry(parent).place(x = 340, y = 180)
self.password = Entry(parent).place(x = 340, y = 250)
self.img_label = PhotoImage(file = 'new-dip-project\\label-image.png')
self.name = Label(parent, image = self.img_label, text = "Email:", bg = '#3c3a3b').place(x = 197,y = 178)
self.img_label_pass = PhotoImage(file = 'new-dip-project\\label_pass.png')
self.name = Label(parent, image = self.img_label_pass, text = "Password:", bg = '#3c3a3b').place(x = 177,y = 245)
def create_pass(self):
self.password_length = Label(self.root2, text = '')
self.password_length.place(x = 80, y = 140)
self.pass_word = str(self.password2.get()) #this code is getting the users input from the password entry box
if len(self.pass_word) >= 8: #if the characters gotten from the pasword entry is less than 8, an erorr message will appear
self.registered = Label(self.root2, text = 'You have successfully registered, this window will now automatically close', font=("open sans", "8"))
self.registered.place(x = 80, y = 140)
self.root2.after(4000, self.root2.destroy)
else:
self.password_length.configure(text="""Your password must be atleast eight characters long. Please try again""", font=("open sans", "8"))
def save_info(self):
self.email_reg = str(self.email2.get())
print(self.email2)
file = open('emails.txt', 'w')
file.write(str(self.email2))
def create_email(self):
self.username_length = Label(self.root2, text = '', font = '40')
self.username_length.place(x = 165, y = 140)
self.email_reg = str(self.email2.get())
if len(self.email_reg) >= 1: #if user has inputted a letter or number it will allow it to go to the next function
self.save_info()
self.create_pass()
self.username_length.destroy()
else:
self.username_length.configure(text='Please enter your username or password', font=("open sans", "8"))
self.username_length.after(3000, self.username_length.destroy)
def openNewWindow(self):
# Toplevel object which will
# be treated as a new window
self.root2 = Toplevel(root)
# sets the title of the
# Toplevel widget
self.root2.title("New Window")
# sets the geometry of toplevel
self.root2.geometry("500x300")
self.load2 = Image.open('new-dip-project\\registerscreen3.jpg')
self.render2 = ImageTk.PhotoImage(self.load2)
self.img2 = Label(self.root2, image = self.render2)
self.img2.place(x = -2, y =0)
self.img_label2 = PhotoImage(file = 'new-dip-project\\label-image.png')
self.name = Label(self.root2, image = self.img_label, bg = '#292929').place(x = 130,y = 102)
self.img_label_pass2 = PhotoImage(file = 'new-dip-project\\label_pass.png')
self.name = Label(self.root2, image = self.img_label_pass, bg = '#292929').place(x = 120,y = 173)
self.email2 = Entry(self.root2)
self.email2.place(x = 280, y = 104)
self.password2 = Entry(self.root2)
self.password2.place(x = 280, y = 180)
self.img_register2 = PhotoImage(file = 'new-dip-project\\register.png')
self.b3 = Button(self.root2,image = self.img_register2, command = self.create_email, bd = 0, bg = '#0d0d0d', activebackground = '#0d0d0d')
self.b3.place(x = 180, y = 250)
self.img_reg2 = PhotoImage(file = 'new-dip-project\\regtitle.png')
self.name9 = Label(self.root2, image = self.img_reg2, bg = '#131313')
self.name9.place(x = 109, y = 10)
if __name__ == "__main__":
e = Goode_brothers(root)
root.title('Goode brothers')
root.mainloop()
Using var = StringVar() to set option textvariable - var when initialize Entry, and get content of Entry by var.get().
example Code
from tkinter import *
def on_click():
print(entry_text.get())
root = Tk()
font = ("Courier New", 32)
entry_text = StringVar()
entry = Entry(root, textvariable=entry_text, font=font)
entry.place(x=0, y=0)
button = Button(root, text='Check', command=on_click, font= font)
button.place(x=0, y=64)
root.mainloop()
Following statement will get value None for self.email
self.email = Entry(parent).place(x = 340, y = 180)
should be
self.email = Entry(parent)
self.email.place(x = 340, y = 180)

Write text into canvas python tkinter

I have all the gui configurations and all that stuff in my main.py and my algorithms to draw bubble sort and merge sort in another .py file. I'm trying to write the print functions into my canvas but I'm not sure how to do it, can anyone help? I tried using a ListBox() but it messes up the main canvas for some reason.
This is my code for my main file:
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from bubbleSort import bubbleSort
from mergeSort import mergeSort
tk = Tk()
tk.title('Examen Final')
tk.maxsize(900, 600)
tk.config(bg = 'black')
algoritmo = StringVar()
data = []
def dibujar(data, color):
c.delete("all")
cHeight = 380
cWidth = 600
algoWidth = cWidth / (len(data) + 1)
algoHeight = cWidth / (len(data) + 1)
offset = 20
spacing = 10
tamData = [i / max(data) for i in data]
for i, height in enumerate(tamData):
x0 = i * algoWidth + offset + spacing
y0 = cHeight - height * 50
x1 = (i+1) * algoWidth + offset
y1 = cHeight
c.create_oval(x0,y0,x1,y1, fill = color[i])
c.create_text(x0+2,y0, anchor = SW, text=str(data[i]))
tk.update_idletasks()
def Ordenar():
print("Se selecciono: " + algoritmo.get())
print("Iniciando algoritmo")
global data
if menu.get() == 'MERGE SORT':
mergeSort(data, dibujar)
elif menu.get() == 'BUBBLE SORT':
bubbleSort(data, dibujar)
dibujar(data, ['green' for x in range(len(data))])
def agregar():
global data
input = int(inputVal.get())
inputVal.delete(0, END)
try:
print("valor input:")
print(input)
data.append((input))
print(str(data))
dibujar(data, ['red' for x in range(len(data))])
except:
messagebox.showerror("Error", "Ingrese un valor numerico")
def limpiar():
global data
data = []
c.delete("all")
print(data)
box = Frame(tk, width = 600, height = 200, bg = 'black' )
box.grid(row = 0, column = 0, padx=10, pady=5)
c = Canvas(tk, width = 600, height = 380, bg = 'grey')
c.grid(row = 1, column = 0, padx=10, pady=5)
c2 = Canvas(tk, width = 200, height = 380, bg = 'grey')
c2.grid(row = 1, column = 1, padx=10, pady=5)
label = Label(box, text='Lista Algoritmos: ', font = ("Arial",15), borderwidth=1, bg = "black" , fg = 'white')
label.grid(row=0,column=0, padx=5, pady=5, sticky = W)
menu = ttk.Combobox(box, textvariable = algoritmo, values=['BUBBLE SORT', 'MERGE SORT', 'HASH TABLES', 'ARBOL AVL', 'ARBOLES ROJO Y NEGRO'])
menu.grid(row=0, column=1, padx=5, pady=5)
menu.current(0)
botonStart = Button(box, text = 'Ordenar', command = Ordenar, bg = 'lime green')
botonStart.grid(row = 0, column = 2, padx = 5, pady = 5)
label = Label(box, text='Insertar valor: ', font = ("Arial",15), borderwidth=1, bg = "black" , fg = 'white')
label.grid(row=1,column=0, padx = 5, pady = 5, sticky = W)
inputVal = Entry(box)
inputVal.grid(row=1,column=1, padx = 5, pady = 5, sticky = W)
botonAdd = Button(box, text = 'Agregar', command = agregar, bg = 'lime green')
botonAdd.grid(row = 1, column = 2, padx = 5, pady = 5, sticky = W)
botonClear = Button(box, text = 'Limpiar', command = limpiar, bg = 'lime green')
botonClear.grid(row = 1, column = 3, padx = 5, pady = 5, sticky = W)
tk.mainloop()
and this is my bubbleSort.py
import time
def bubbleSort(data, dibujar):
for _ in range(len(data)-1):
for j in range(len(data)-1):
if data[j] > data[j+1]:
print(("El numero " + str(data[j]) + " es mayor que " + str(data[j+1])))
data[j],data[j+1] = data[j+1], data[j]
print(("Intercambiando de lugar " + str(data[j]) + " con " + str(data[j+1])))
dibujar(data,
[
'green'
if x == j or x == j+1
else 'red' for x in range(len(data))
]
)
time.sleep(1)
dibujar(data, ['green' for x in range(len(data))])
You can just pass in c2 to the function on the other file. So first define the parameter:
def bubbleSort(data, dibujar, cnv):
cnv.create_text(100,100,text='Trial Text')
....
Now each time you call this function, pass on c2 to it.
if menu.get() == 'BUBBLE SORT':
bubbleSort(data, dibujar, c2)
I did notice that you are using dynamic points for calculation, if so, make those points global, inside the function, then pass those onto the function by creating more parameter, while keeping in mind that the points have to defined before the function is called.

Using tkinter IntVar to update a label

Having taken a class on C and Assembly, I decided I wanted to learn python. This is my first attempt with it so please excuse any abuse of notation.
The following is the portion of my GUI I have created to control a grow cycle. I am having an issue with the use IntVar. I have created a countdown to the end-of-cycle (see countdown method). I have tried including the self.remaining label within Countdown, it does show the countdown but the label showing the countdown does not destroy with the cancel button and time_state label at end-of-cycle. With the self.remaining label put in the init using IntVar, it shows the initial countdown in days,hours, mins,secs but stays with that initial value and does not update as countdown is repeated. Shouldn't using IntVar this way update the day_val, hour_val, min_val, and sec_val in the self.remaining label?
from tkinter import *
import time
class Grow_Cycle():
def __init__(self):
self.time_state = Label(app, text = ("You have selected:\n "+str(day_val)+" days,\n "+str(hour_val)+" hours,\n "+str(min_val)+" minutes"))
self.time_state.grid(column = 1, row =1)
self.bttn_3 = Button(app, text = "Cancel", command = self.cancel)
self.bttn_3.configure(bg = "red")
self.bttn_3.grid(row = 2, column = 0,
ipadx = 50, ipady = 20,
padx = 20, pady = 100)
self.temp1 = (day_val * 86400)+(hour_val * 3600)+(min_val * 60)
self.countdown()
self.remaining = Label(app, text = ("You have remaining:\n"+str(day_lef.get())+" days,\n"
+str(hour_lef.get())+" hours,\n"
+str(min_lef.get())+" minutes,\n"
+str(sec_lef.get())+" seconds"),
textvariable = (day_lef, hour_lef, min_lef, sec_lef))
self.remaining.grid(column = 1, row = 2)
def cancel(self):
self.remaining.destroy()
self.bttn_3.destroy()
self.time_state.destroy()
self.temp1 = 0
def countdown(self):
if self.temp1 > 0:
self.temp1 -= 1
global day_lef
day_lef = IntVar()
day_lef.set(int(self.temp1 / 86400))
day_rem = self.temp1 % 86400
global hour_lef
hour_lef = IntVar()
hour_lef.set(int(day_rem / 3600))
hour_rem = day_rem % 3600
global min_lef
min_lef = IntVar()
min_lef.set(int(hour_rem / 60))
min_rem = hour_rem % 60
global sec_lef
sec_lef = IntVar()
sec_lef.set(int(min_rem % 60))
clock.after(1000, self.countdown)
else:
self.cancel()
def tick():
global time1
time2 = time.strftime('%H:%M:%S\n\n%m-%d-%Y')
if time2 != time1:
time1 = time2
clock.config(text=time2)
clock.after(200, tick)
def grow():
# Grow Time set window
set_grow_time = Toplevel(app)
set_grow_time.title("Enter Cycle Time")
set_grow_time.geometry("240x400")
# Set Day
set_day_grow = Spinbox(set_grow_time, from_ = 0, to_ = 10)
set_day_grow.grid(column = 0, row =0,
padx = 20, pady = 20)
set_day_grow.config(width = 10)
set_day_lbl = Label(set_grow_time, text = "Set Day: 0 to 10")
set_day_lbl.grid(column = 1, row = 0)
# Set Hour
set_hour_grow = Spinbox(set_grow_time, from_ = 0, to_ = 23)
set_hour_grow.grid(column = 0, row = 1,
padx = 20, pady = 20)
set_hour_grow.config(width = 10)
set_hour_lbl = Label(set_grow_time, text = "Set Hour: 0 to 23")
set_hour_lbl.grid(column = 1, row = 1)
# Set Minute
set_min_grow = Spinbox(set_grow_time, from_ = 0, to_ = 59)
set_min_grow.grid(column = 0, row = 2,
padx = 20, pady = 20)
set_min_grow.config(width = 10)
set_hour_lbl = Label(set_grow_time, text = "Set Minute: 0 to 59")
set_hour_lbl.grid(column = 1, row = 2)
# Confirm Selection
def fetch_time():
global day_val
day_val = int(set_day_grow.get())
global hour_val
hour_val = int(set_hour_grow.get())
global min_val
min_val = int(set_min_grow.get())
Grow_Cycle()
confirm_grow_time = Button(set_grow_time, text = "OK", command = lambda: (fetch_time(), set_grow_time.destroy()))
confirm_grow_time.grid(column = 0, row = 3)
cancel_grow_time = Button(set_grow_time, text = "Cancel", command = set_grow_time.destroy)
cancel_grow_time.grid(column = 1, row = 3)
def clean():
pass # will finish later
def cancel():
pass # will finish later
# main
# Main Loop Begin
root = Tk()
root.title("Grower")
root.geometry("1280x720")
app = Frame(root)
app.grid()
time1 = ''
clock = Label(app)
clock.config(font = ("Impact", 20))
clock.grid(column = 1, row = 0,
ipadx = 20, ipady = 20,
padx = 50, pady =50)
# Button Setup
bttn_1 = Button(app, text = "Grow", command = grow)
bttn_1.configure(bg = "light green")
bttn_1.grid(column = 0, row = 0,
ipadx = 50, ipady = 20,
padx = 20, pady = 100)
bttn_2 = Button(app, text = "Clean", command = clean)
bttn_2.configure(bg = "cyan")
bttn_2.grid(row = 1, column = 0,
ipadx = 50, ipady = 20,
padx = 20, pady = 100)
tick()
root.mainloop()
After reviewing your code I have made some changes to how you are formatting your strings and how you are apply strings to your labels.
Your class def was not working for me so I rewrote it with a standard method I use to create a tkinter class.
I don't believe you can have both a text = "string' and a textvariable = StringVar() at the same time. So I have formatted the data into your string var.
The way you had it set up it would not work for a few reason. You cant use multiple IntVar()'s in a textvariable so you need to first combine them into a string variable and then use that as your update method to the label.
I have changed your string concatination removing the + method and using format() instead as this is the correct method currently.
I also added self.string_var.set to your countdown() method so we can keep this updated with the countdown.
Take a look at this code and let me know if you have any question.
import tkinter as tk
class Grow_Cycle(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self.master = master
self.day_val = 1
self.hour_val = 0
self.min_val = 0
self.day_lef = tk.IntVar()
self.day_lef.set(1)
self.hour_lef = tk.IntVar()
self.hour_lef.set(0)
self.min_lef = tk.IntVar()
self.min_lef.set(0)
self.sec_lef = tk.IntVar()
self.sec_lef.set(0)
self.day_rem = 0
self.hour_rem = 0
self.min_rem = 0
self.string_var = tk.StringVar()
self.string_var2 = tk.StringVar()
self.string_var.set(
"You have remaining:\n{} days,\n{} hours,\n{} minutes,\n{} seconds".format(self.day_lef.get(), self.hour_lef.get(), self.min_lef.get(), self.sec_lef.get()))
self.time_state = tk.Label(self.master, text = (
"You have selected:\n {} days,\n {} hours,\n {} minutes").format(self.day_val, self.hour_val, self.min_val))
self.time_state.grid(row = 1, column = 1)
self.bttn_3 = tk.Button(self.master, bg = "red", text = "Cancel", command = self.cancel)
self.bttn_3.grid(row = 2, column = 0, ipadx = 50, ipady = 20, padx = 20, pady = 100)
self.temp1 = (self.day_val * 86400)+(self.hour_val * 3600)+(self.min_val * 60)
self.remaining = tk.Label(self.master, textvariable = self.string_var)
self.remaining.grid(column = 1, row = 2)
self.countdown()
def cancel(self):
self.remaining.destroy()
self.bttn_3.destroy()
self.time_state.destroy()
self.temp1 = 0
def countdown(self):
self.string_var.set(
"You have remaining:\n{} days,\n{} hours,\n{} minutes,\n{} seconds".format(self.day_lef.get(), self.hour_lef.get(), self.min_lef.get(), self.sec_lef.get()))
if self.temp1 > 0:
self.temp1 -= 1
self.day_lef.set(int(self.temp1 / 86400))
self.day_rem = self.temp1 % 86400
self.hour_lef.set(int(self.day_rem / 3600))
self.hour_rem = self.day_rem % 3600
self.min_lef.set(int(self.hour_rem / 60))
self.min_rem = self.hour_rem % 60
self.sec_lef.set(int(self.min_rem % 60))
root.after(1000, self.countdown)
else:
self.cancel()
if __name__ == "__main__":
root = tk.Tk()
Grow_Cycle(root)
root.mainloop()

Categories