Related
I tried adding a text file to store all the data by building a function that opens and writes data to the file, the code seems to run but no data is getting added to the text file.
Here is the tkinter code.
name = StringVar()
email = StringVar()
usn = StringVar()
namelabel = ttk.Label(frame_content, text='Name',font=('Poppins', 10))
namelabel.grid(row=0, column=0, sticky='sw', padx=(2,10))
entry_name = ttk.Entry(frame_content, width=30, font=('Poppins', 10), textvariable=name)
entry_name.grid(row=1, column=0)
emaillabel = ttk.Label(frame_content, text='Email',font=('Poppins', 10))
emaillabel.grid(row=0, column=1, sticky='sw', padx=10)
entry_email = ttk.Entry(frame_content, width=30, font=('Poppins', 10), textvariable=email)
entry_email.grid(row=1, column=1, padx=10)
usnlabel = ttk.Label(frame_content, text='USN',font=('Poppins', 10))
usnlabel.grid(row=0, column=2, sticky='sw')
entry_usn = ttk.Entry(frame_content, width=30, font=('Poppins', 10), textvariable=usn)
entry_usn.grid(row=1, column=2)
feedbacklabel = ttk.Label(frame_content, text='Feedback', font=('Poppins', 10))
feedbacklabel.grid(row=2, column=0, sticky='sw', pady=5)
textfeedback = Text(frame_content, width=94, height=15, font=('Poppins', 10))
textfeedback.grid(row=3, column=0, columnspan=3)
def submit():
print('Name:{}'.format(name.get()))
print('USN:{}'.format(usn.get()))
print('Email:{}'.format(email.get()))
print('Feedback:{}'.format(textfeedback.get(1.0, END)))
messagebox.showinfo(title='Submit', message='Thank you for your Feedback')
entry_name.delete(0, END)
entry_email.delete(0, END)
entry_usn.delete(0, END)
textfeedback.delete(1.0, END)
def open_file():
name_info = name.get()
email_info = email.get()
usn_info = usn.get()
feed_info = textfeedback.get(1.0, END)
data_file = open("data.txt", 'w')
data_file.write(name_info)
data_file.write(email_info)
data_file.write(usn_info)
data_file.write(feed_info)
data_file.close()
submitbutton = ttk.Button(root, width=25, text='Submit', command=lambda: [submit(), open_file()])
mainloop()
EDIT
Your mistake can be at
submitbutton = ttk.Button(root, width=25, text='Submit', command=lambda: [submit(), open_file()])
Call open_file() function first, then call submit() function, like:
submitbutton = ttk.Button(root, width=25, text='Submit', command=lambda: [open_file(), submit()])
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()
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()
from tkinter import *
win=Tk()
var = StringVar()
l = Label(win, bg='white', width=15)
l.grid(row=17,column=1,padx=10, pady=10, sticky='w')
def print1_selection():
if var.get()=="Number":
lab1= Label(win, text="Enter a number").grid(row=4, column=0)
ent1=Entry(win).grid(row=4, column=1)
l.config(text='you have selected ' + var.get())
elif var.get()=="Alphabet":
lab21= Label(win, text="Enter an alphabet").grid(row=5, column=0)
ent21=Entry(win).grid(row=5, column=1)
l.config(text='you have selected ' + var.get())
lbl4=Label(win, text="Select One", bg="crimson", fg="white", font=("times new
roman",15,"bold")).grid(row=1, column=0, padx=10, pady=10, sticky='w')
r1 = Radiobutton(win, text='Number',variable=var, value='Number', command=print1_selection, width=22)
r1.grid(row=2,column=0,padx=10, pady=10)
r2 = Radiobutton(win, text='Alphabet', variable=var, value='Alphabet', command=print1_selection, width=22)
r2.grid(row=2,column=1,padx=10, pady=10)
win.mainloop()
In this code I want that when I select radiobutton number, only enter a number should appear and same for the other.
But the problem is that when I select number after selecting alphabet, it shows both. I need only the selected one and eliminate the other instantly.
This is how I would approach this issue:
from tkinter import Tk, StringVar, Label, Frame, Entry, Radiobutton
def print1_selection():
for widget in entry_frame.winfo_children():
widget.destroy()
value = var.get()
lbl.config(text='You have selected ' + value)
if value == "Number":
Label(entry_frame, text="Enter a number").grid(row=0, column=0)
Entry(entry_frame).grid(row=0, column=1)
elif value == "Alphabet":
Label(entry_frame, text="Enter an alphabet").grid(row=0, column=0)
Entry(entry_frame).grid(row=0, column=1)
win = Tk()
var = StringVar(value=0)
entry_frame = Frame(win)
entry_frame.grid(row=2, column=0, columnspan=2)
lbl = Label(win, bg='white', width=20)
lbl.grid(row=3, column=0, columnspan=2, padx=10, pady=10, sticky='w')
Label(win, text="Select One", bg="crimson", fg="white", font=("times new roman", 15, "bold")).grid(row=0, column=0, padx=10, pady=10, sticky='w')
Radiobutton(win, text='Number', variable=var, value='Number', command=print1_selection, width=22).grid(row=1, column=0, padx=10, pady=10)
Radiobutton(win, text='Alphabet', variable=var, value='Alphabet', command=print1_selection, width=22).grid(row=1, column=1, padx=10, pady=10)
win.mainloop()
As You can see if You don't plan on using the widgets instance anywhere You don't have to assign it to a variable. Also no need to configure label in both statements since that will be done anyways so just do it at the beginning, also rows start from 0 too. Frames help with organizing widgets. Also if You want neither of the radiobuttons selected set the variable to 0.
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()