Getting multiple results with one button (python/ tkiner) - python

I'm a beginner, and I've gathered a number of reference sites to make code!
But if you click the button, you'll see the value only for the last item.
Do you happen to know how to get each result in every row! And now you have to enter all the items to get the value, but even if there is a blank, I hope the result will come out for all the input boxes.
I think the code is a little tangled, but it's hard to solve. I'm posting the code's full text.
from tkinter import *
from tkinter import ttk
import csv
class App(ttk.Frame):
num_rows = 2
entry_list = []
def __init__(self, master, *args, **kwargs):
ttk.Frame.__init__(self, master, *args, **kwargs)
self.master = master
self.label_frame = ttk.Frame(self.master)
self.label_frame.grid()
self.label_list = []
label1 = Label(root, width=5, text="No.")
label2 = Label(root, width=12, text="Chip")
label3 = Label(root, width=12, text="Length[mm] : ")
label4 = Label(root, width=12, text="Width[mm] : ")
label5 = Label(root, width=12, text="Height[mm] : ")
label6 = Label(root, width=12, text="Watt[W] : ")
label7 = Label(root, width=12, text="Rjc[C/W] : ")
label8 = Label(root, width=12, text="h[W/㎡K] : ")
label9 = Label(master, width=12, text="Temp[C] : ",fg='red')
#grid
label1.grid(row=0, column=0, padx=1, pady=10)
label2.grid(row=0, column=1, padx=2, pady=10)
label3.grid(row=0, column=2, padx=2, pady=10)
label4.grid(row=0, column=3, padx=2, pady=10)
label5.grid(row=0, column=4, padx=2, pady=10)
label6.grid(row=0, column=5, padx=2, pady=10)
label7.grid(row=0, column=6, padx=2, pady=10)
label8.grid(row=0, column=7, padx=2, pady=10)
label9.grid(row=0, column=8, padx=2, pady=10)
##유동
self.Number_field = Entry(root, width=5)
self.Length_field = Entry(root, width=9)
self.Width_field = Entry(root, width=9)
self.Height_field = Entry(root, width=9)
self.Watt_field = Entry(root, width=9)
self.Rjc_field = Entry(root, width=9)
self.Temperature_field = Entry(root, width=9)
self.Number_field.grid(row=1, column=0, padx=1, pady=1)
self.Length_field.grid(row=1, column=2, padx=1, pady=1)
self.Width_field.grid(row=1, column=3, padx=1, pady=1)
self.Height_field.grid(row=1, column=4, padx=1, pady=1)
self.Watt_field.grid(row=1, column=5, padx=1, pady=1)
self.Rjc_field.grid(row=1, column=6, padx=1, pady=1)
self.Temperature_field.grid(row=1, column=8, padx=1, pady=1)
strs = StringVar()
strs2 = StringVar()
combx1 = ttk.Combobox(root, width=9, textvariable=strs)
combx1['values'] = (' Natural', ' Forced(Fan)')
combx1.current()
combx1.grid(column=7, row=1)
combx2 = ttk.Combobox(root, width=9, textvariable=strs2)
combx2['values'] = ('CPU', 'eMMC', 'PMIC')
combx2.grid(column=1, row=1)
combx2.current()
# Create a Submit Button and attached
button1 = Button(root, text="Submit", bg="black", fg="white", command=self.cal_Temp)
button1.grid(row=100, column=0, pady=10)
button2 = Button(root, text="Clear", fg="blue", command=self.clear_all)
button2.grid(row=100, column=1, pady=10)
button3 = Button(root, text="Add Row (+)", command=self.add_new)
button3.grid(row=102, column=0, pady=10)
button4 = Button(root, text="Delete Row (-)", command=self.delete)
button4.grid(row=102, column=1, pady=10)
button5 = Button(root, text="Export", command=self.writeToFile)
button5.grid(row=103, column=1, pady=10)
def writeToFile(self):
with open('Temperature_MJH.csv', 'a') as f:
w=csv.writer(f, quoting=csv.QUOTE_ALL)
w.writerow([self.Length_field.get()])
w.writerow([self.Width_field.get()])
w.writerow([self.Height_field.get()])
w.writerow([self.Watt_field.get()])
w.writerow([self.Rjc_field.get()])
w.writerow([self.Temperature_field.get()])
def clear_all(self):
self.Number_field.delete(0,END)
self.Length_field.delete(0, END)
self.Width_field.delete(0, END)
self.Height_field.delete(0, END)
self.Watt_field.delete(0, END)
self.Rjc_field.delete(0, END)
self.Temperature_field.delete(0, END)
#이거 지워도 되는지
self.Length_field.focus_set()
def cal_Temp(self):
Length = float(self.Length_field.get())
Width = float(self.Width_field.get())
Height = float(self.Height_field.get())
Watt = float(self.Watt_field.get())
Rjc = float(self.Rjc_field.get())
h = 1
Temperature = float(((Watt * 0.5) / (((Length * Width * 2) + (Length * 2) + (
Height * Width * 5)) / 1000)) / h + Rjc )
self.Temperature_field.insert(10,Temperature)
print(Temperature)
def add_new(self):
self.num_rows += 1
self.Number_field = Entry(root, width=5)
self.Length_field = Entry(root, width=9)
self.Width_field = Entry(root, width=9)
self.Height_field = Entry(root, width=9)
self.Watt_field = Entry(root, width=9)
self.Rjc_field = Entry(root, width=9)
self.Temperature_field = Entry(root, width=9)
self.Number_field.grid(row=self.num_rows, column=0, padx=1, pady=1)
self.Length_field.grid(row=self.num_rows, column=2, padx=1, pady=1)
self.Width_field.grid(row=self.num_rows, column=3, padx=1, pady=1)
self.Height_field.grid(row=self.num_rows, column=4, padx=1, pady=1)
self.Watt_field.grid(row=self.num_rows, column=5, padx=1, pady=1)
self.Rjc_field.grid(row=self.num_rows, column=6, padx=1, pady=1)
self.Temperature_field.grid(row=self.num_rows, column=8, padx=1, pady=1)
strs = StringVar()
strs2 = StringVar()
self.combx1 = ttk.Combobox(root, width=9, textvariable=strs)
self.combx1['values'] = (' Natural', ' Forced(Fan)')
self.combx1.current()
self.combx1.grid(row=self.num_rows, column=7)
self.combx2 = ttk.Combobox(root, width=9, textvariable=strs2)
self.combx2['values'] = ('CPU', 'eMMC', 'PMIC')
self.combx2.grid(row=self.num_rows, column=1)
self.combx2.current()
self.ics=self.num_rows
self.Number_field.insert(10, self.ics-1)
def delete(self):
self.num_rows -= 1
self.Number_field.destroy()
self.Length_field.destroy()
self.Width_field.destroy()
self.Height_field.destroy()
self.Watt_field.destroy()
self.Rjc_field.destroy()
self.Temperature_field.destroy()
self.combx1.destroy()
self.combx2.destroy()
self.ics -= 1
if __name__ == "__main__":
root = Tk()
root.configure(background='snow')
root.geometry("1000x450")
root.title("Expectation of Temp Calculator")
my_app = App(root)
root.mainloop()

Related

tkinter clickable Label to open details of Label [duplicate]

This question already has answers here:
tkinter creating buttons in for loop passing command arguments
(3 answers)
Closed 6 months ago.
I'm trying to program an interface with tkinter, that shows users of my application as a list of Labels. The list is created from a database (created with sqlite3).
By clicking on each Label the program should open another window, showing details of the clicked user.
maybe do I need to use classes? (because for now, my script is not OOP)
root = Tk()
root.title("Utenti")
root.iconbitmap("D:\Willow\WilloW SW Gestionale")
root.geometry("365x600")
def open_user(name = str):
user = Tk()
user.title("Utenti")
user.iconbitmap("D:\Willow\WilloW SW Gestionale")
user.geometry("500x400")
#create entry
f_name_entry = Entry(user, width=30, state="disabled")
f_name_entry.grid(row=0, column=1, padx=20, pady=(10, 0))
P_iva_entry = Entry(user, width=30, state="disabled")
P_iva_entry.grid(row=1, column=1)
cell_number_entry = Entry(user, width=30, state="disabled")
cell_number_entry.grid(row=2, column=1)
tax_entry = Entry(user, width=30, state="disabled")
tax_entry.grid(row=3, column=1)
inps_entry = Entry(user, width=30, state="disabled")
inps_entry.grid(row=4, column=1)
# create text boxes
f_name_label = Label(user, text=name)
f_name_label.grid(row=0, column=0, pady=(10, 0))
P_iva_label = Label(user, text="p iva")
P_iva_label.grid(row=1, column=0)
cell_number_label = Label(user, text="cell number")
cell_number_label.grid(row=2, column=0)
tax_label = Label(user, text="tax")
tax_label.grid(row=3, column=0)
inps_label = Label(user, text="inps")
inps_label.grid(row=4, column=0)
i = 4
conn = sqlite3.connect("usersEsteso.db")
c = conn.cursor()
c.execute("SELECT *, oid FROM usersEsteso")
records = c.fetchall()
for record in records:
print_records = record[0]
users_lable = Label(root, bg="#778899")
users_lable.grid(row=i + 7, column=0, sticky="w", padx=5, pady=5, columnspan=3)
user_text = Label(users_lable, text=print_records)
user_text.grid(row=0, column=0, pady=5, padx=5, sticky="w")
#user_text.bind("<Enter>", open_user("sam"))
openUser_lable_button = Button(users_lable, text="apri " + record[0], command=lambda: open_user(record[0])) #here i showld pass the identification of the parent the button
openUser_lable_button.grid(row=1, column=0, pady=5, padx=5, sticky="e")
i = i + 1
conn.commit()
conn.close()
here the previous code, without database and simplyfied:
from tkinter import *
root = Tk()
root.title("Users")
root.geometry("365x600")
#global variables
i = 1
def open_user():
user = Tk()
user.title("User")
user.geometry("500x400")
#create entry
f_name_entry = Entry(user, width=150, state="normal")
f_name_entry.grid(row=0, column=1, padx=20, pady=(10, 0))
P_iva_entry = Entry(user, width=150, state="disabled")
P_iva_entry.grid(row=1, column=1, columnspan=2)
cell_number_entry = Entry(user, width=150, state="disabled")
cell_number_entry.grid(row=2, column=1, columnspan=2)
tax_entry = Entry(user, width=150, state="disabled")
tax_entry.grid(row=3, column=1, columnspan=2)
inps_entry = Entry(user, width=150, state="disabled")
inps_entry.grid(row=4, column=1, columnspan=2)
# create text boxes
f_name_label = Label(user, text="name")
f_name_label.grid(row=0, column=0, pady=(10, 0))
P_iva_label = Label(user, text="p iva")
P_iva_label.grid(row=1, column=0)
cell_number_label = Label(user, text="cell number")
cell_number_label.grid(row=2, column=0)
tax_label = Label(user, text="tax")
tax_label.grid(row=3, column=0)
inps_label = Label(user, text="inps")
inps_label.grid(row=4, column=0)
f_name_entry.insert(0, "here should be the name of the clicked user")
my_list = ["andrew", "sam", "Zoe"]
title_label = Label(root, text="List of Users")
title_label.grid(row=0, column=0, pady=(10,40))
for item in my_list:
print(i)
my_frame = Frame(root, bg="#a6a6a6")
my_label = Label(my_frame, text=item)
my_button = Button(my_frame, text="inspect user", command=open_user)
my_frame.grid(row=i, column=0, padx=10, pady=10)
my_label.grid(row=0, column=0, padx=10, pady=10)
my_button.grid(row=1, column=0, padx=10, pady=10)
i = i+1
root.mainloop()

trying to print cost total of my menu gui in tkinter. ERROR = 'int' object is not callable

Hi i have had trouble trying to make this menu chat bot kind of thing into a gui, i have mismatched a bit of code and i can print the total cost of all items once clicked 'Finish Order' in line 108
All Code:
from tkinter import *
cost = 0
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master, bg='#DA291C')
self.master = master
self.init_window()
def init_window(self):
self.master.title("Maccas Menu")
self.pack(fill=BOTH, expand=1)
Label(self, bg='#DA291C', text=" Name: ",fg='#FFC72C').grid(row=0)
Label(self, bg='#DA291C', text="Address: ",fg='#FFC72C').grid(row=1)
Label(self, bg='#DA291C', text="Phone: ",fg='#FFC72C').grid(row=2)
#Customer Details
self.Name = Entry(self)
self.Name.grid(row=0, column=1)
self.Address = Entry(self, state='disabled')
self.Address.grid(row=1, column=1)
self.Phone_Number = Entry(self, state='disabled')
self.Phone_Number.grid(row=2, column=1)
self.delivery = BooleanVar()
Checkbutton(self, text="Delivery",fg='#27251F', bg='#DA291C', variable=self.delivery, command=self.check).grid(row=1, column=2)
Button(self, text='Show',fg='#27251F', bg='#DA291C', command=self.show_entry_fields).grid(row=0, column=2, sticky=W, pady=4, padx=5)
#Maccas Selection
Label(self, text = "Maccas", font='bold', fg='#27251F', bg='#DA291C').grid(columnspan=2, pady=(20,5))
#Maccas Numbers
self.BigMac_num = IntVar()
self.Nuggets_num = IntVar()
self.AngusBurger_num = IntVar()
self.Wraps_num = IntVar()
self.SoftServe_num = IntVar()
self.Fillet_o_Fish_num = IntVar()
self.HappyMeal_num = IntVar()
self.Salad_num = IntVar()
self.Sprite_num_num = IntVar()
self.Frozen_Coke_num = IntVar()
self.Apple_Pie_num = IntVar()
self.Apple_Slices_num = IntVar()
#Spinbox Labels
Label(self, text = "BigMac",fg='#FFC72C', bg='#DA291C').grid(row=4)
Label(self, text = "Nuggets",fg='#FFC72C', bg='#DA291C').grid(row=5)
Label(self, text = "AngusBurger",fg='#FFC72C', bg='#DA291C').grid(row=6)
Label(self, text = "Wraps",fg='#FFC72C', bg='#DA291C').grid(row=7)
Label(self, text = "SoftServe",fg='#FFC72C', bg='#DA291C').grid(row=8)
Label(self, text = "Fillet'o'Fish",fg='#FFC72C', bg='#DA291C').grid(row=9)
Label(self, text = "HappyMeal",fg='#FFC72C', bg='#DA291C').grid(row=10)
Label(self, text = "Salad",fg='#FFC72C', bg='#DA291C').grid(row=11)
Label(self, text = "Sprite",fg='#FFC72C', bg='#DA291C').grid(row=12)
Label(self, text = "Frozen Coke",fg='#FFC72C', bg='#DA291C').grid(row=13)
Label(self, text = "Apple Pie",fg='#FFC72C', bg='#DA291C').grid(row=14)
Label(self, text = "Apple Slices",fg='#FFC72C', bg='#DA291C').grid(row=15)
#Spinboxes
self.BigMac_num = Spinbox(self, from_=0, to=5)
self.Nuggets_num = Spinbox(self, from_=0, to=5)
self.AngusBurger_num = Spinbox(self, from_=0, to=5)
self.Wraps_num = Spinbox(self, from_=0, to=5)
self.SoftServe_num = Spinbox(self, from_=0, to=5)
self.Fillet_o_Fish_num = Spinbox(self, from_=0, to=5)
self.HappyMeal_num = Spinbox(self, from_=0, to=5)
self.Salad_num = Spinbox(self, from_=0, to=5)
self.Sprite_num = Spinbox(self, from_=0, to=5)
self.Frozen_Coke_num = Spinbox(self, from_=0, to=5)
self.Apple_Pie_num = Spinbox(self, from_=0, to=5)
self.Apple_Slices_num = Spinbox(self, from_=0, to=5)
#Spinbox Positioning
self.BigMac_num.grid(row=4, column=1)
self.Nuggets_num.grid(row=5, column=1)
self.AngusBurger_num.grid(row=6, column=1)
self.Wraps_num.grid(row=7, column=1)
self.SoftServe_num.grid(row=8, column=1)
self.Fillet_o_Fish_num.grid(row=9, column=1)
self.HappyMeal_num.grid(row=10, column=1)
self.Salad_num.grid(row=11, column=1)
self.Sprite_num.grid(row=12, column=1)
self.Frozen_Coke_num.grid(row=13, column=1)
self.Apple_Pie_num.grid(row=14, column=1)
self.Apple_Slices_num.grid(row=15, column=1)
self.Total_Maccas_num = IntVar()
Button(self, text='Finish Order',fg='#27251F',bg='#DA291C', command=self.Maccas_Submit).grid(row=16, column=0, sticky=W, pady=4, padx=5)
self.TooMany = Label(self, text = "Less than 5 items please.")
self.TooMany.grid_remove()
def Maccas_Submit(self):
self.Total_Maccas_num = int(self.BigMac_num.get()) + int(self.Nuggets_num.get()) + int(self.AngusBurger_num.get()) + int(self.Wraps_num.get()) + int(self.SoftServe_num.get()) + int(self.Fillet_o_Fish_num.get()) + int(self.HappyMeal_num.get()) + int(self.Salad_num.get()) + int(self.Sprite_num.get()) + int(self.Frozen_Coke_num.get()) + int(self.Apple_Pie_num.get()) + int(self.Apple_Slices_num.get())
if int(self.Total_Maccas_num) > 5:
self.TooMany.grid(row=20, column=1)
else:
self.Total_Maccas_num(row=20, column=1)
def check(self):
if self.delivery.get() == True:
self.Address.configure(state='normal')
self.Phone_Number.configure(state='normal')
else:
self.Address.configure(state='disabled')
self.Phone_Number.configure(state='disabled')
def show_entry_fields(self):
global cost
print("\n Name: {}\n Address: {}\n Phone Number: {}" .format(self.Name.get(), self.Address.get(), self.Phone_Number.get()))
print(self.delivery.get())
if self.delivery.get() == True:
cost += 3
print(cost)
root = Tk()
root.geometry("400x600")
app = Window(root)
root.mainloop()
here is the section i am confused about and would like some help with.
def Maccas_Submit(self):
self.Total_Maccas_num = int(self.BigMac_num.get()) + int(self.Nuggets_num.get()) + int(self.AngusBurger_num.get()) + int(self.Wraps_num.get()) + int(self.SoftServe_num.get()) + int(self.Fillet_o_Fish_num.get()) + int(self.HappyMeal_num.get()) + int(self.Salad_num.get()) + int(self.Sprite_num.get()) + int(self.Frozen_Coke_num.get()) + int(self.Apple_Pie_num.get()) + int(self.Apple_Slices_num.get())
if int(self.Total_Maccas_num) > 5:
self.TooMany.grid(row=20, column=1)
else:
self.Total_Maccas_num(row=20, column=1)
if anyone can solve this problem it would help a lot thanks.
Inside Maccas_Submit(), you have changed self.Total_Maccas_num from IntVar (initialized inside init_window()) to int:
def Maccas_Submit(self):
# below line changed self.Total_Maccas_num to 'int'
self.Total_Maccas_num = int(self.BigMac_num.get()) + int(self.Nuggets_num.get()) + int(self.AngusBurger_num.get()) + int(self.Wraps_num.get()) + int(self.SoftServe_num.get()) + int(self.Fillet_o_Fish_num.get()) + int(self.HappyMeal_num.get()) + int(self.Salad_num.get()) + int(self.Sprite_num.get()) + int(self.Frozen_Coke_num.get()) + int(self.Apple_Pie_num.get()) + int(self.Apple_Slices_num.get())
if int(self.Total_Maccas_num) > 5:
self.TooMany.grid(row=20, column=1)
else:
# below line tries to use 'int' as a function which causes the exception
self.Total_Maccas_num(row=20, column=1)
Based on your code, I would suggest the following changes:
class Window(Frame):
...
def init_window(self):
...
self.Total_Maccas_num = IntVar()
Button(self, text='Finish Order',fg='#27251F',bg='#DA291C', command=self.Maccas_Submit).grid(row=16, column=0, sticky=W, pady=4, padx=5)
self.TooMany = Label(self, text = "Less than 5 items please.")
#self.TooMany.grid_remove() # not necessary
self.total_label = Label(self, textvariable=self.Total_Maccas_num) # added a label for the total
def Maccas_Submit(self):
total = int(self.BigMac_num.get()) + int(self.Nuggets_num.get()) + int(self.AngusBurger_num.get()) + int(self.Wraps_num.get()) + int(self.SoftServe_num.get()) + int(self.Fillet_o_Fish_num.get()) + int(self.HappyMeal_num.get()) + int(self.Salad_num.get()) + int(self.Sprite_num.get()) + int(self.Frozen_Coke_num.get()) + int(self.Apple_Pie_num.get()) + int(self.Apple_Slices_num.get())
if total > 5:
self.total_label.grid_forget() # hide the total_label
self.TooMany.grid(row=20, column=1) # show the warning
else:
self.TooMany.grid_forget() # hide the warning
self.Total_Maccas_num.set(total) # update total_label
self.total_label.grid(row=20, column=1) # show total_label
I can't really explain it so here's an example:
#This is my own Python Grade Percentage Calculator
import tkinter
root = tkinter.Tk()
root.title("Calculator")
root.configure(background="red")
expression =""
def add(value):
global expression
expression += value
label_result.config(text=expression)
def clear():
global expression
expression = ""
label_result.config(text=expression)
def calculate():
global expression
result = ""
if expression != "":
try:
result = format(eval(expression), ".2f")
except:
result = "Invalid Entry"
expression = ""
label_result.config(text=result)
# Create GUI
label_result = tkinter.Label(root, height=3, text="JOEL'S \n GRADE CALCULATOR \n",fg="#FFFFFF", bg="red", font="Calibri 20 bold")
label_result.grid(row=0, column=0, columnspan=3)
label_result = tkinter.Label(root, height=2, text="",fg="#FFFFFF", bg="red", font="verdana 15 bold")
label_result.grid(row=1, column=0, columnspan=3)
button_1 = tkinter.Button(root, text="1", height=4, width=20, command=lambda: add("1"))
button_1.grid(row=2, column=0)
button_2 = tkinter.Button(root, text="2", height=4, width=20, command=lambda: add("2"))
button_2.grid(row=2, column=1)
button_3 = tkinter.Button(root, text="3", height=4, width=20, command=lambda: add("3"))
button_3.grid(row=2, column=2)
button_4 = tkinter.Button(root, text="4", height=4, width=20, command=lambda: add("4"))
button_4.grid(row=3, column=0)
button_5 = tkinter.Button(root, text="5", height=4, width=20, command=lambda: add("5"))
button_5.grid(row=3, column=1)
button_6 = tkinter.Button(root, text="6", height=4, width=20, command=lambda: add("6"))
button_6.grid(row=3, column=2)
button_7 = tkinter.Button(root, text="7", height=4, width=20, command=lambda: add("7"))
button_7.grid(row=4, column=0)
button_8 = tkinter.Button(root, text="8", height=4, width=20, command=lambda: add("8"))
button_8.grid(row=4, column=1)
button_9 = tkinter.Button(root, text="9", height=4, width=20, command=lambda: add("9"))
button_9.grid(row=4, column=2)
button_clear = tkinter.Button(root, text="CLEAR", height=4, width=20, command=lambda: clear())
button_clear.grid(row=5, column=0)
button_0 = tkinter.Button(root, text="0", height=4, width=20, command=lambda: add("0"))
button_0.grid(row=5, column=1)
button_dot = tkinter.Button(root, text=".", height=4, width=20, command=lambda: add("."))
button_dot.grid(row=5, column=2)
button_equals = tkinter.Button(root, fg="#000000", text=" / ", width=33, bg="red", font="Calibri 12 bold", command=lambda: add ("/"))
button_equals.grid(row=6, column=0, columnspan=3)
button_equals = tkinter.Button(root, fg="#000000", text="CONVERT TO PERCENTAGE", width=33,bg="red", font="Calibri 12 bold", command=lambda: add ("*100"))
button_equals.grid(row=7, column=0, columnspan=3)
button_equals = tkinter.Button(root, fg="#000000", text=" = ",bg="red", width=33, font="Calibri 12 bold", command=lambda: calculate())
button_equals.grid(row=8, column=0, columnspan=3)
root.mainloop()

Python Tkinter, How to pass Variable into mutltiple Functions

EDIT: Thanks to #Osadhi Virochana Jayasinghe Si! Using global "vars" inside the buildwindow() function, makes them readable in the called button function. I also had to fix how to get the Values of the Checkbox and text Widget.
Full Fixed code:
import tkinter as tk
import tkinter.scrolledtext as tkst
from PyQt5.QtWidgets import QApplication # need to install PyQt5 or remove center() Function
def main_window():
window = tk.Tk()
window.title("New Entry")
build_window(window)
center(window) # https://stackoverflow.com/questions/3352918/how-to-center-a-window-on-the-screen-in-tkinter
window.mainloop() # Main Loop, nothing runs after here on Gui
def center(toplevel):
toplevel.update_idletasks()
app = QApplication([])
screen_width = app.desktop().screenGeometry().width()
screen_height = app.desktop().screenGeometry().height()
size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
x = screen_width/2 - size[0]/2
y = screen_height/2 - size[1]/2
toplevel.geometry("+%d+%d" % (x, y))
def build_window(window):
global entry_name, entry_link, entry_xpath, chbox_active, entry_comment, box_var
label_title = tk.Label(window, text="NEW ENTRY")
label_name = tk.Label(window, text="Name:")
entry_name = tk.Entry(window)
label_link = tk.Label(window, text="Link:")
entry_link = tk.Entry(window)
label_xpath = tk.Label(window, text="XPath:")
entry_xpath = tk.Entry(window)
label_active = tk.Label(window, text="Active:")
box_var = tk.IntVar()
chbox_active = tk.Checkbutton(window, variable=box_var, text="Active")
label_comment = tk.Label(window, text="Comment:")
entry_comment = tkst.ScrolledText(window, width=40, height=4, font=("roboto", 8))
botton_cancel = tk.Button(window, text="Done", command=lambda: close_window(window))
button_go = tk.Button(window, text="Run", command=lambda: write_dict(window))
label_title.grid (row=0, column=1, sticky="nwse", padx=2, pady=2)
label_name.grid (row=1, column=0, sticky="e", padx=2, pady=2)
entry_name.grid (row=1, column=1, sticky="nwse", padx=2, pady=2)
label_link.grid (row=2, column=0, sticky="e", padx=2, pady=2)
entry_link.grid (row=2, column=1, sticky="nwse", padx=2, pady=2)
label_xpath.grid (row=3, column=0, sticky="e", padx=2, pady=2)
entry_xpath.grid (row=3, column=1, sticky="nwse", padx=2, pady=2)
label_active.grid (row=4, column=0, sticky="e", padx=2, pady=2)
chbox_active.grid (row=4, column=1, sticky="w", padx=2, pady=2)
label_comment.grid (row=5, column=0, sticky="e", padx=2, pady=2)
entry_comment.grid (row=5, column=1, sticky="w", padx=2, pady=2)
window.grid_rowconfigure(6, minsize=20) # Empty?
botton_cancel.grid(row=7, column=0, sticky="w", padx=2, pady=2) # Cancel Button
button_go.grid(row=7, column=1, sticky="e", padx=2, pady=2) # Write Dict Button
def close_window(window):
window.destroy()
def write_dict(window):
i_dict = {}
i_dict["name"] = entry_name.get()
i_dict["link"] = entry_link.get()
i_dict["xpath"] = entry_xpath.get()
i_dict["active"] = box_var.get()
i_dict["comment"] = entry_comment.get('1.0', tk.END)
print(i_dict)
pass
main_window()
I am trying to make a simple GUI do enter Data into a Dictionary. Most things i find online write the Tkinter straight into the .py, but i want to use a Function to Draw the Window, and another Function to do its stuff once a Button is pressed.
Shorted code:
def main_window():
window = tk.Tk()
build_window(window)
window.mainloop()
def build_window(window):
entry_name = tk.Entry(window)
button_go = tk.Button(window, text="Run", command=lambda: write_dict())
button_go.grid(row=7, column=1, sticky="e", padx=2, pady=2)
def write_dict():
i_dict = {}
i_dict["name"] = entry_name.get()
main_window()
And i am getting AttributeError: module 'tkinter' has no attribute 'entry_name'. I tried various ways to get window into write_dict(), but i could never use .get() to read the values inside the Entry Box.
how would i do this?
Full code:
import tkinter as tk
import tkinter.scrolledtext as tkst
from PyQt5.QtWidgets import QApplication
d_list = []
def main_window():
window = tk.Tk()
window.title("New Entry")
build_window(window)
window.mainloop() # Main Loop, nothing runs after here on Gui
def build_window(window):
label_title = tk.Label(window, text="NEW ENTRY")
label_name = tk.Label(window, text="Name:")
entry_name = tk.Entry(window)
label_link = tk.Label(window, text="Link:")
entry_link = tk.Entry(window)
label_xpath = tk.Label(window, text="XPath:")
entry_xpath = tk.Entry(window)
label_active = tk.Label(window, text="Active:")
chbox_active = tk.Checkbutton(window, variable=1, text="Active")
label_comment = tk.Label(window, text="Comment:")
entry_comment = tkst.ScrolledText(window, width=40, height=4, font=("roboto", 8))
botton_cancel = tk.Button(window, text="Done", command=lambda: close_window(window))
button_go = tk.Button(window, text="Run", command=lambda: write_dict())
label_title.grid (row=0, column=1, sticky="nwse", padx=2, pady=2)
label_name.grid (row=1, column=0, sticky="e", padx=2, pady=2)
entry_name.grid (row=1, column=1, sticky="nwse", padx=2, pady=2)
label_link.grid (row=2, column=0, sticky="e", padx=2, pady=2)
entry_link.grid (row=2, column=1, sticky="nwse", padx=2, pady=2)
label_xpath.grid (row=3, column=0, sticky="e", padx=2, pady=2)
entry_xpath.grid (row=3, column=1, sticky="nwse", padx=2, pady=2)
label_active.grid (row=4, column=0, sticky="e", padx=2, pady=2)
chbox_active.grid (row=4, column=1, sticky="w", padx=2, pady=2)
label_comment.grid (row=5, column=0, sticky="e", padx=2, pady=2)
entry_comment.grid (row=5, column=1, sticky="w", padx=2, pady=2)
window.grid_rowconfigure(6, minsize=20) # Empty?
botton_cancel.grid(row=7, column=0, sticky="w", padx=2, pady=2) # Cancel Button
button_go.grid(row=7, column=1, sticky="e", padx=2, pady=2) # Write Dict Button
def close_window(window):
window.destroy()
def write_dict():
global d_list
i_dict = {}
i_dict["name"] = entry_name.get()
i_dict["link"] = entry_link.get()
i_dict["xpath"] = entry_xpath.get()
i_dict["active"] = chbox_active.get()
i_dict["comment"] = entry_comment.get()
print(i_dict)
pass
main_window()
EDIT:
The Full Errors are these 2, the first one is with the currently posted code, the second is with passing ´window´ into the button.
Traceback (most recent call last):
File "C:\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:/Users/Chris/Google Drive/Python/html_new_entry.py", line 50, in <lambda>
button_go = tk.Button(window, text="Run", command=lambda: write_dict())
File "C:/Users/Chris/Google Drive/Python/html_new_entry.py", line 78, in write_dict
i_dict["name"] = entry_name.get()
NameError: name 'entry_name' is not defined
Traceback (most recent call last):
File "C:\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:/Users/Chris/Google Drive/Python/html_new_entry.py", line 50, in <lambda>
button_go = tk.Button(window, text="Run", command=lambda: write_dict(window))
File "C:/Users/Chris/Google Drive/Python/html_new_entry.py", line 78, in write_dict
i_dict["name"] = window.entry_name.get()
File "C:\Python\Python38\lib\tkinter\__init__.py", line 2345, in __getattr__
return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'entry_name'
Add global entry_name,entry_link,entry_xpath,chbox_active,entry_comment under the def build_window(window): It will fix Variable error.
And I fixed all of the issues
Here is the Code:
import tkinter as tk
import tkinter.scrolledtext as tkst
#from PyQt5.QtWidgets import QApplication
d_list = []
def main_window():
window = tk.Tk()
window.title("New Entry")
build_window(window)
window.mainloop() # Main Loop, nothing runs after here on Gui
def build_window(window):
global entry_name,entry_link,entry_xpath,chbox_active,entry_comment,var
var = tk.IntVar()
label_title = tk.Label(window, text="NEW ENTRY")
label_name = tk.Label(window, text="Name:")
entry_name = tk.Entry(window)
label_link = tk.Label(window, text="Link:")
entry_link = tk.Entry(window)
label_xpath = tk.Label(window, text="XPath:")
entry_xpath = tk.Entry(window)
label_active = tk.Label(window, text="Active:")
chbox_active = tk.Checkbutton(window, variable=var, text="Active")
label_comment = tk.Label(window, text="Comment:")
entry_comment = tkst.ScrolledText(window, width=40, height=4, font=("roboto", 8))
botton_cancel = tk.Button(window, text="Done", command=lambda: close_window(window))
button_go = tk.Button(window, text="Run", command=lambda: write_dict())
label_title.grid (row=0, column=1, sticky="nwse", padx=2, pady=2)
label_name.grid (row=1, column=0, sticky="e", padx=2, pady=2)
entry_name.grid (row=1, column=1, sticky="nwse", padx=2, pady=2)
label_link.grid (row=2, column=0, sticky="e", padx=2, pady=2)
entry_link.grid (row=2, column=1, sticky="nwse", padx=2, pady=2)
label_xpath.grid (row=3, column=0, sticky="e", padx=2, pady=2)
entry_xpath.grid (row=3, column=1, sticky="nwse", padx=2, pady=2)
label_active.grid (row=4, column=0, sticky="e", padx=2, pady=2)
chbox_active.grid (row=4, column=1, sticky="w", padx=2, pady=2)
label_comment.grid (row=5, column=0, sticky="e", padx=2, pady=2)
entry_comment.grid (row=5, column=1, sticky="w", padx=2, pady=2)
window.grid_rowconfigure(6, minsize=20) # Empty?
botton_cancel.grid(row=7, column=0, sticky="w", padx=2, pady=2) # Cancel Button
button_go.grid(row=7, column=1, sticky="e", padx=2, pady=2) # Write Dict Button
def close_window(window):
window.destroy()
def write_dict():
global d_list
i_dict = {}
v = ""
i_dict["name"] = entry_name.get()
i_dict["link"] = entry_link.get()
i_dict["xpath"] = entry_xpath.get()
i_dict["active"] = var.get()
i_dict["comment"] = entry_comment.get('1.0', 'end-1c')
print(i_dict)
pass
main_window()
Now you can get checkbox status and comment box status too.

Python search CSV file and return result in Tkinter

Question has been updated since I've received an answer.
The question that now raises is how to get the values from the csv file when I have two "Players" next to each other.
from Tkinter import *
import csv
master = Tk()
b1 = StringVar()
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
b2 = StringVar()
v4 = StringVar()
v5 = StringVar()
v6 = StringVar()
a = Label(master, text="Player 1", font="Verdana 10 bold").grid(row=8, column=1, columnspan=2, pady=15)
b = Label(master, text="Player Name").grid(row=9, column=1, sticky='w')
c = Label(master, text="1st Service Percentage:").grid(row=10, column=1, sticky='w')
cc = Label(master, text="value", textvariable=v1)
d = Label(master, text="Points Won on 1st Serve: ").grid(row=11, column=1, sticky='w')
dd = Label(master, text="value", textvariable=v2)
e = Label(master, text="Points Won on 2nd serve:").grid(row=12, column=1, sticky='w')
ee = Label(master, text="value", textvariable=v3)
a22 = Label(master, text="Player 2", font="Verdana 10 bold").grid(row=8, column=3, columnspan=2, pady=15)
b22 = Label(master, text="Player Name").grid(row=9, column=3, sticky='w')
c22 = Label(master, text="1st Service Percentage:").grid(row=10, column=3, sticky='w')
cc22 = Label(master, text="value", textvariable=v4)
d22 = Label(master, text="Points Won on 1st Serve: ").grid(row=11, column=3, sticky='w')
dd22 = Label(master, text="value", textvariable=v5)
e22 = Label(master, text="Points Won on 2nd serve:").grid(row=12, column=3, sticky='w')
ee22 = Label(master, text="value", textvariable=v6)
def name():
with open("Service.csv") as fh:
for row in fh:
if (b1.get()) in row:
player_name = row[0:row.find(',')]
row = row.replace(player_name+',', '')
firstService = row[0:row.find(",")]
row = row.replace(firstService+',', '')
points_firstserve = row[0:row.find(",")]
row = row.replace(points_firstserve+',', '')
points_secondserve = row[0:row.find(",")]
row = row.replace(points_secondserve+',', '')
v1.set(firstService)
cc.grid(row=10, column=2, sticky='w')
v2.set(points_firstserve)
dd.grid(row=11, column=2, sticky='w')
v3.set(points_secondserve)
ee.grid(row=12, column=2, sticky='w')
if (b2.get()) in row:
player_name = row[0:row.find(',')]
row = row.replace(player_name + ',', '')
firstService = row[0:row.find(",")]
row = row.replace(firstService + ',', '')
points_firstserve = row[0:row.find(",")]
row = row.replace(points_firstserve + ',', '')
points_secondserve = row[0:row.find(",")]
row = row.replace(points_secondserve + ',', '')
v1.set(firstService)
cc.grid(row=10, column=2, sticky='w')
v2.set(points_firstserve)
dd.grid(row=11, column=2, sticky='w')
v3.set(points_secondserve)
ee.grid(row=12, column=2, sticky='w')
myb1 = Entry(master, textvariable=b1)
myb1.insert(10, "Andy Murray")
myb1.grid(row=9, column=2)
myb22 = Entry(master, textvariable=b2)
myb22.insert(10, "Novak Djokovic")
myb22.grid(row=9, column=4)
button1 = Button(master, text='Run', command=name, bg="light green", font="Verdana 9 bold")
button2 = Button(master, text='Quit', command=quit, bg="red", font="Verdana 9 bold")
button1.grid(row=15, column=2, ipadx=50, pady=10)
button2.grid(row=15, column=3, ipadx=50, pady=10, padx=5)
master.geometry("850x500+300+100")
master.bind('<Return>', name)
master.bind('<Escape>', quit)
mainloop()
Here I am not using v1,v2 and v3 text variables. Appending second player values beside first player values.
Enter "Andy Murray" hit Run next Enter "Novak Djokovic"
hit run. you will see results of second player beside first player values.
from tkinter import *
import csv
master = Tk()
b1 = StringVar()
#v1 = StringVar()
#v2 = StringVar()
#v3 = StringVar()
a = Label(master, text="Player 1", font="Verdana 10 bold").grid(row=8, column=1, columnspan=2, pady=15)
b = Label(master, text="Player Name").grid(row=9, column=1, sticky='w')
c = Label(master, text="1st Service Percentage:").grid(row=10, column=1, sticky='w')
cc = Label(master, text="")
d = Label(master, text="Points Won on 1st Serve: ").grid(row=11, column=1, sticky='w')
dd = Label(master, text="")
e = Label(master, text="Points Won on 2nd serve:").grid(row=12, column=1, sticky='w')
ee = Label(master, text="")
def name():
with open("service.csv") as fh:
for row in fh:
if (b1.get()) in row:
player_name = row[0:row.find(',')]
row=row.replace(player_name+',','')
#print(row)
firstService=row[0:row.find(",")]
row=row.replace(firstService+',','')
points_firstserve=row[0:row.find(",")]
row=row.replace(points_firstserve+',','')
points_secondserve=row[0:row.find(",")]
row=row.replace(points_secondserve+',','')
cc['text'] += " "+firstService
#v1.set(firstService)
cc.grid(row=10, column=2, sticky='w')
#v2.set(points_firstserve)
dd['text'] += " "+points_firstserve
dd.grid(row=11, column=2, sticky='w')
#v3.set(points_secondserve)
ee['text'] += " "+points_secondserve
ee.grid(row=12, column=2, sticky='w')
myb1 = Entry(master, textvariable=b1)
myb1.insert(10, "Andy Murray")
myb1.grid(row=9, column=2)
button1 = Button(master, text='Run', command=name, bg="light green", font="Verdana 9 bold")
button2 = Button(master, text='Quit', command=quit, bg="red", font="Verdana 9 bold")
button1.grid(row=15, column=2, ipadx=50, pady=10)
button2.grid(row=15, column=3, ipadx=50, pady=10, padx=5)
master.geometry("850x500+300+100")
master.bind('<Return>', name)
master.bind('<Escape>', quit)
mainloop()
from tkinter import *
import csv
master = Tk()
b1 = StringVar()
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
a = Label(master, text="Player 1", font="Verdana 10 bold").grid(row=8, column=1, columnspan=2, pady=15)
b = Label(master, text="Player Name").grid(row=9, column=1, sticky='w')
c = Label(master, text="1st Service Percentage:").grid(row=10, column=1, sticky='w')
cc = Label(master, text="value", textvariable=v1)
d = Label(master, text="Points Won on 1st Serve: ").grid(row=11, column=1, sticky='w')
dd = Label(master, text="value", textvariable=v2)
e = Label(master, text="Points Won on 2nd serve:").grid(row=12, column=1, sticky='w')
ee = Label(master, text="value", textvariable=v3)
def name():
with open("Service.csv") as fh:
for row in fh:
if (b1.get()) in row:
player_name = row[0:row.find(',')]
row=row.replace(player_name+',','')
#print(row)
firstService=row[0:row.find(",")]
row=row.replace(firstService+',','')
points_firstserve=row[0:row.find(",")]
row=row.replace(points_firstserve+',','')
points_secondserve=row[0:row.find(",")]
row=row.replace(points_secondserve+',','')
#
v1.set(firstService)
cc.grid(row=10, column=2, sticky='w')
v2.set(points_firstserve)
dd.grid(row=11, column=2, sticky='w')
v3.set(points_secondserve)
ee.grid(row=12, column=2, sticky='w')
myb1 = Entry(master, textvariable=b1)
myb1.insert(10, "Andy Murray")
myb1.grid(row=9, column=2)
button1 = Button(master, text='Run', command=name, bg="light green", font="Verdana 9 bold")
button2 = Button(master, text='Quit', command=quit, bg="red", font="Verdana 9 bold")
button1.grid(row=15, column=2, ipadx=50, pady=10)
button2.grid(row=15, column=3, ipadx=50, pady=10, padx=5)
master.geometry("850x500+300+100")
master.bind('<Return>', name)
master.bind('<Escape>', quit)
mainloop()
This will fetch numbers from csv row for specific player. Am placing the value beside value names in the GUI.
Hope this helps.

Python tkinter, clearing an Entry widget from a class

This is the class I'm calling and the function from a different file
class CalcFunc:
def clearScreen(self):
self.log("CLEAR (CE)")
ent.delete(0, END)
This is the Entry Box
ent = Entry(root, textvariable=clc.getBtn, justify=RIGHT, font=10, relief=RIDGE, bd=2, width=15)
ent.grid(row=0, columnspan=3, pady=10)
This is the button I'm clicking to clear the Entry Box
buttonCC = Button(root, text="CLEAR (CE)", height=1, width=20, bg='orange', command=clc.clearScreen)
I'm not sure what the syntax is to be able to to clear an Entry widget from a class basically. That code worked when I had it in the same file but my project requires it to be in a separate file. It's a class project for a calculator and the "clear" button clears the Entry widget. I can post my entire code if that helps. Thank you.
----EDIT----
My Class
import time
class CalcFunc:
def log(self, val):
myFile = open(r".\log.dat", "a")
myFile.write("%s\n" % val)
myFile.close()
def onScreen(self, iVal):
self.log(iVal)
currentTxt = self.getBtn.get()
updateEnt = self.getBtn.set(currentTxt + iVal)
def clearScreen(self):
self.log("CLEAR (CE)")
ent.delete(0, END)
def evaL(self):
self.log("=")
self.getBtn.set(str(eval(self.getBtn.get())))
self.log(self.getBtn.get())
def logLbl(self):
myFile = open(r".\log.dat", "a")
myFile.write("\n==================================\n")
myFile.write("Date: " + str(time.strftime("%m/%d/%Y")) + " -- Time: " + str(time.strftime("%I:%M:%S")))
myFile.write("\n==================================\n")
myFile.close()
My Program
from tkinter import *
import time
import clcClass
root = Tk()
root.title('skClc v1')
clc = clcClass.CalcFunc()
clc.logLbl()
clc.getBtn = StringVar()
ent = Entry(root, textvariable=clc.getBtn, justify=RIGHT, font=10, relief=RIDGE, bd=2, width=15)
ent.grid(row=0, columnspan=3, pady=10)
button1 = Button(root, text="1", height=1, width=5, bg='light blue', command=lambda:clc.onScreen('1'))
button2 = Button(root, text="2", height=1, width=5, bg='light blue', command=lambda:clc.onScreen('2'))
button3 = Button(root, text="3", height=1, width=5, bg='light blue', command=lambda:clc.onScreen('3'))
button4 = Button(root, text="4", height=1, width=5, bg='light blue', command=lambda:clc.onScreen('4'))
button5 = Button(root, text="5", height=1, width=5, bg='light blue', command=lambda:clc.onScreen('5'))
button6 = Button(root, text="6", height=1, width=5, bg='light blue', command=lambda:clc.onScreen('6'))
button7 = Button(root, text="7", height=1, width=5, bg='light blue', command=lambda:clc.onScreen('7'))
button8 = Button(root, text="8", height=1, width=5, bg='light blue', command=lambda:clc.onScreen('8'))
button9 = Button(root, text="9", height=1, width=5, bg='light blue', command=lambda:clc.onScreen('9'))
button0 = Button(root, text="0", height=1, width=5, bg='light blue', command=lambda:onScreen('0'))
buttonP = Button(root, text="+", height=1, width=5, bg='gray', command=lambda:clc.onScreen('+'))
buttonM = Button(root, text="-", height=1, width=5, bg='gray', command=lambda:clc.onScreen('-'))
buttonMM = Button(root, text="x", height=1, width=5, bg='gray', command=lambda:clc.onScreen('*'))
buttonDD = Button(root, text="÷", height=1, width=5, bg='gray', command=lambda:clc.onScreen('/'))
buttonEE = Button(root, text="=", height=1, width=5, bg='light green', command=clc.evaL)
buttonCC = Button(root, text="CLEAR (CE)", height=1, width=20, bg='orange', command=clc.clearScreen)
button1.grid(row=1, column=0, pady=5)
button2.grid(row=1, column=1, pady=5)
button3.grid(row=1, column=2, pady=5)
button4.grid(row=2, column=0, pady=5)
button5.grid(row=2, column=1, pady=5)
button6.grid(row=2, column=2, pady=5)
button7.grid(row=3, column=0, pady=5)
button8.grid(row=3, column=1, pady=5)
button9.grid(row=3, column=2, pady=5)
button0.grid(row=4, column=0, pady=5)
buttonP.grid(row=4, column=1, pady=5)
buttonM.grid(row=4, column=2, pady=5)
buttonEE.grid(row=5, column=0, pady=5)
buttonDD.grid(row=5, column=1, pady=5)
buttonMM.grid(row=5, column=2, pady=5)
buttonCC.grid(row=6, column=0, pady=5, columnspan=3)
root.maxsize(140,245);
root.minsize(140,245);
root.mainloop()
ent = Entry(root, ....)
clc = clcClass.CalcFunc(ent)
class CalcFunc:
def __init__(self, entry):
self.entry = entry
def clearScreen(self):
self.log("CLEAR (CE)")
self.entry.delete(0, END)
Here's an abbreviated example:
#my_entry.py
from tkinter import END
import time
class EntryWithLogger:
def __init__(self, entry):
self.entry = entry
def log(self, val):
with open("log.dat", "a") as my_file: #Automatically closes the file--even if an exception occurs, which is not the case with my_file.close().
my_file.write("%s\n" % val)
def onScreen(self, i_val):
self.log(i_val)
self.entry.insert(END, i_val)
def clearScreen(self):
self.log("CLEAR (CE)")
self.entry.delete(0, END)
Note that I didn't use a StringVar(), which doesn't appear to be necessary. If you need it, you can always pass it as an argument to __init__(), then store it on self.
import my_entry as me
import tkinter as tk
root = tk.Tk()
root.title("Calculator")
root.geometry("+100+50") #("300x500+200+10") dimension, position
entry = tk.Entry(root, justify=tk.RIGHT, font=10, relief=tk.RIDGE, bd=2, width=15)
entry.grid(row=0, columnspan=3, pady=10)
entry_with_logger = me.EntryWithLogger(entry)
#Create the buttons in a loop:
for i in range(10):
row_num, col_num = divmod(i, 3) #divmod(7, 2) => (3, 1), divmod(0, 3) => (0, 0), divmod(4, 3) => (1, 1)
row_num += 1
button_text = str(i)
tk.Button(root, text=button_text,
height=1,
width=5,
bg='light blue',
command=lambda x=button_text: entry_with_logger.onScreen(x)
).grid(row=row_num, column=col_num, pady=5)
#Put the clear button at the bottom of the grid:
tk.Button(root, text="CLEAR (CE)",
height=1,
width=20,
bg='orange',
command=entry_with_logger.clearScreen
).grid(row=row_num+1, columnspan=3) #columnspan tells grid() to use 3 cells for the button,
#and the button will be centered by default.
root.mainloop()
Or, you could do it like this:
#my_entry.py
from tkinter import Entry, END
import time
class EntryWithLogger(Entry):
#Because __init__() is not implemented, the parent class's __init__() gets
#called, so you create an EntryWithLogger just like you would an Entry.
def log(self, val):
with open("log.dat", "a") as my_file: #Automatically closes the file--even if there is an exception, which is not the case with my_file.close().
my_file.write("%s\n" % val)
def onScreen(self, i_val):
self.log(i_val)
self.insert(END, i_val)
def clearScreen(self):
self.log("CLEAR (CE)")
self.delete(0, END)
import my_entry as me
import tkinter as tk
root = tk.Tk()
root.title("Calculator")
root.geometry("+100+50") #("300x500+200+10") dimension, position
entry = me.EntryWithLogger(root, justify=tk.RIGHT, font=10, relief=tk.RIDGE, bd=2, width=15)
entry.grid(row=0, columnspan=3, pady=10)
#Create the buttons in a loop:
for i in range(10):
row_num, col_num = divmod(i, 3) #divmod(7, 2) => (3, 1), divmod(0, 3) => (0, 0), divmod(4, 3) => (1, 1)
row_num += 1
button_text = str(i)
tk.Button(root, text=button_text,
height=1,
width=5,
bg='LightBlue',
command=lambda x=button_text: entry.onScreen(x)
).grid(row=row_num, column=col_num, pady=5)
#Put the clear button at the bottom of the grid:
tk.Button(root, text="CLEAR (CE)",
height=1,
width=20,
bg='orange',
command=entry.clearScreen
).grid(row=row_num+1, columnspan=3) #columnspan tells grid() to use 3 cells for the button,
#and the button will be centered by default.
root.mainloop()

Categories