Related
*First of all, i am trying to create a register system saved into textfile(not real system, i know its not safe to write into textfiles) Created the GUI and then i defined multiple functions which is Menu, register and submit. Submit function is nested and inside register function. The problem is when i nested the functions it doesn't write into textfiles, but when i delete the register function, it works.
When i press register and write something in the Entry box, it didnt record to the text files, i have been scratching my head as to find what the error in my code is.
Edit: I now have put a picture to get better understanding. the blue window is main menu and its the mainloop and the yellow window is appearing when i click register button.*
picture of what should be my app
from tkinter import *
def Register():
def Submit():
elev = open("bruker.txt","a", encoding="utf-8")
elev.write(brukeridinc.get()+"\n")
elev.write(fornavn.get()+"\n")
elev.write(etternavn.get()+"\n")
register = Tk()
register.geometry("500x500")
register.configure(bg="yellow")
register.title("Bibliotekapp Login")
label_brukerid = Label(register, text="Brukerid:", bg="white", font=("Arial", 25))
label_brukerid.grid(row=1, column=0, padx=5, pady=5, sticky=E)
label_fornavn = Label(register, text="Fornavn:", bg="white", font=("Arial", 25))
label_fornavn.grid(row=2, column=0, padx=5, pady=5, sticky=E)
label_etternavn = Label(register, text="Etternavn:", bg="white", font=("Arial", 25))
label_etternavn.grid(row=3, column=0, padx=5, pady=5, sticky=E)
brukeridinc= StringVar()
entry_brukerid= Entry(register, width=10, textvariable=brukeridinc, font=("Arial", 25))
entry_brukerid.grid(row=1, column=1, padx=5, pady=5, sticky=W)
fornavn= StringVar()
entry_fornavn= Entry(register, width=10, textvariable=fornavn, font=("Arial", 25))
entry_fornavn.grid(row=2, column=1, padx=5, pady=5, sticky=W)
etternavn= StringVar()
entry_etternavn= Entry(register, width=10, textvariable=etternavn, font=("Arial", 25))
entry_etternavn.grid(row=3, column=1, padx=5, pady=5, sticky=W)
button_resultat= Button(register, text="Enter", command=Submit, height=2, width=15)
button_resultat.grid(row=4, column=1, padx=5, pady=5, sticky=W)
informasjon= StringVar()
entry_informasjon= Entry(register, width=24, textvariable=informasjon, state="readonly", font=("Arial", 25))
entry_informasjon.grid(row=5, column=1, padx=5, pady=5, sticky=W)
#GUI
start = Tk()
start.geometry("500x500")
start.configure(bg="lightblue")
start.title("Bibliotekapp")
button_register = Button(start, text="Register", bg="white", font=("Arial", 25), command=Register)
button_register.grid(row=5, column=5, padx=5, pady=5, sticky=E)
start.mainloop()
I do not understand how you write code. You are using too many duplicates. I will not going to explain to you. In line 51 and 54 , I changed command to None. You can replace it.
Here is code:
from tkinter import *
start = Tk()
start.geometry("800x500")
start.configure(bg="lightblue")
start.title("Bibliotekapp")
def menu():
start.geometry("500x500")
start.title("Bibliotekapp")
start.configure(bg="red")
def Register():
start.geometry("800x800")
start.configure(bg="yellow")
start.title("Bibliotekapp Login")
def Submit():
elev = open("bruker.txt", "r")
sjekk = elev.read()
if brukeridinc.get() in sjekk:
informasjon.set("User already exists")
else:
elev.close()
elev = open("bruker.txt", "a")
elev.write(brukeridinc.get() + "")
elev.write(fornavn.get() + "")
elev.write(etternavn.get() + "\n")
elev.close()
informasjon.set("You are started")
####### GUI ############
label_brukerid = Label(start, text="Brukerid:", bg="white", font=("Arial", 25))
label_brukerid.grid(row=1, column=0, padx=5, pady=5, sticky=E)
label_fornavn = Label(start, text="Fornavn:", bg="white", font=("Arial", 25))
label_fornavn.grid(row=2, column=0, padx=5, pady=5, sticky=E)
label_etternavn = Label(start, text="Etternavn:", bg="white", font=("Arial", 25))
label_etternavn.grid(row=3, column=0, padx=5, pady=5, sticky=E)
brukeridinc= StringVar()
entry_brukerid= Entry(start, width=10, textvariable=brukeridinc, font=("Arial", 25))
entry_brukerid.grid(row=1, column=1, padx=5, pady=5, sticky=W)
fornavn= StringVar()
entry_fornavn= Entry(start, width=10, textvariable=fornavn, font=("Arial", 25))
entry_fornavn.grid(row=2, column=1, padx=5, pady=5, sticky=W)
etternavn= StringVar()
entry_etternavn= Entry(start, width=10, textvariable=etternavn, font=("Arial", 25))
entry_etternavn.grid(row=3, column=1, padx=5, pady=5, sticky=W)
button_start = Button(start, text="start", bg="white", font=("Arial", 25), command=Submit)
button_start.grid(row=5, column=5, padx=5, pady=5, sticky=E)
button_login = Button(start, text="Login", bg="white", font=("Arial", 25), command=menu)
button_login.grid(row=6, column=5, padx=5, pady=5, sticky=E)
button_lån = Button(start, text="Lån", bg="white", font=("Arial", 25), command=Register)
button_lån.grid(row=7, column=5, padx=5, pady=5, sticky=E)
informasjon= StringVar()
entry_informasjon= Entry(start, width=24, textvariable=informasjon, state="readonly", font=("Arial", 25))
entry_informasjon.grid(row=5, column=1, padx=5, pady=5, sticky=W)
start.mainloop()
Result:
Result Red:
Result for yellow:
I am working on a YouTube downloader project that takes a link and then puts the information about the video quality and sound quality of the link in the Combobox.
But when I try to put audio and video information in the Combobox, it gives this exception:
This is my code :
import tkinter
import tkinter.ttk
from tkinter import *
from tkinter import filedialog
from os import path
import pafy
from pafy import *
class Youtube():
def __init__(self):
self.label()
self.entry()
self.button()
self.combobox()
self.data=[]
def label(self):
Label(window, text='URL', font='bold').grid(row=0, column=0, padx=100)
Label(window, text='Destination', font='bold').grid(row=2, column=0, padx=100)
Label(window, text='File Name', font='bold').grid(row=4, column=0, padx=100)
Label(window, text='Video Quality', font='bold').grid(row=6, column=0, pady=20)
Label(window, text='Audio Quality', font='bold').grid(row=7, column=0, pady=5)
Label(window, text='Download Type', font='bold').grid(row=8, column=0, pady=15)
Label(window, text='Combine AV', font='bold').grid(row=8, column=1)
def entry(self):
global een
global en
en=Entry(window, width=35, borderwidth=10)
en.grid(row=1, column=0, padx=100, pady=5)
een=Entry(window, width=35, borderwidth=10)
een.grid(row=3, column=0, padx=100, pady=5)
Entry(window, width=35, borderwidth=10).grid(row=5, column=0, padx=100, pady=5)
def button(self):
Button(window, text='i', height=1, width=3, command=self.information).grid(row=1, column=1)
Button(window, text='d', height=1, width=3, command=self.destination).grid(row=3, column=1)
Button(window, text='Download', font='bold').grid(row=12, column=0, padx=150, pady=10, columnspan=3)
def combobox(self):
tkinter.ttk.Combobox(window, width=15).grid(row=6, column=1)
tkinter.ttk.Combobox(window, width=15).grid(row=7, column=1, pady=5)
tkinter.ttk.Combobox(window, values=['Audio only', 'Vido only', 'Audio and vido'],
width=15).grid(row=9, column=0)
tkinter.ttk.Combobox(window, values=['Yes', 'No'], width=15).grid(row=9, column=1, pady=20)
tkinter.ttk.Progressbar(window, orient=HORIZONTAL, length=300,
mode='determinate').grid(row=11, column=0, padx=200, pady=10, columnspan=3)
def destination(self):
path = str(filedialog.askdirectory())
een.insert(tkinter.END, path)
def information(self):
global link
link = en.get()
self.video()
self.audio()
def video(self):
video_quality_list = []
self.data = pafy.new(link)
video_streams = self.data.videostreams
for video_quality in video_streams:
video_quality_list.append(video_quality)
tkinter.ttk.Combobox(window, values=video_quality_list, width=15).grid(row=6, column=1, pady=5)
def audio(self):
audio_quality_list = []
self.data = pafy.new(link)
audio_streams = self.data.audiostreams
for audio_quality in audio_streams:
audio_quality_list.append(audio_quality)
tkinter.ttk.Combobox(window, values=audio_quality_list, width=15).grid(row=7, column=1)
window = Tk()
mywin = Youtube()
window.title('Youtube Downloader')
window.geometry("700x600+10+10")
window.mainloop()
I would be very grateful if anyone could help me to fix it.
Thanks!
thanks for helping!
I have a spreadsheet that records my income and expenses, with dates, description, debit and credit amount. I wanted to used openpyxl to automate the process of adding values that are in a particular category, the program kind of works now, but the problem is: when I am searching for a phrase that don't exist in the sheet, the program crash, it can not do the things it suppose to before and after the search phrase that dont exist.
for example,
when i wanted to calculate the subtotal of search phrase "wage" and the put the subtotal into a target cell, it works fine. the problem comes out when i ask the program to look for something that isnt there.
I ask the program to look for wage, and create a subtotal, works fine and suppose to store the value at a defined target, when i ask the program to look for tax (which dont exist) the program showed nothing, then i ask the program to get the subtotal of rent (which exists). The program cant make the changes.
i am relatively new to all this.... so thanks again for helping! :)
from tkinter import *
import openpyxl as xl
window = Tk()
window.title("Excel Automation") # rename the title
def define_subtotal():
file_name = str(file_name_input_field.get()) # Collects the text from the text entry box
sheet_name = str(sheet_name_label_name_input_field.get()) # Collects the text from the text entry box
global wb # declare Workbook as global variable
wb = xl.load_workbook(file_name) # define workbook
sheet = wb[sheet_name] # Define sheet name
col_num = int(search_column_input_field.get())
search_phrase = search_phrase_input_field.get()
offset_col = int(offset_col_input_field.get())
target_col_num = int(target_col_input_field.get())
target_row_num = int(target_row_input_field.get())
total = 0
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, col_num)
if cell.value is None:
continue
else:
if search_phrase.casefold() in str(cell.value).casefold():
total += cell.offset(column=offset_col).value
total_description = sheet.cell(target_row_num, target_col_num + 1)
total_description.value = "Subtotal of : " + search_phrase
total_cell = sheet.cell(target_row_num, target_col_num)
total_cell.value = total
output.delete(0.0, END)
output.insert(END, "Subtotal for " + search_phrase + " defined")
else:
continue
def execute():
output.delete(0.0, END) # clear the text box
new_file_name = new_file_input_field.get()
output.insert(END, "Calculations complete!")
wb.save(new_file_name + ".xlsx")
def import_excel_file():
output.delete(0.0, END) # clear the text box
output.insert(END, "File imported")
sheet_name_label_name_input_field.config (state='disabled')
import_button.config (state='disabled')
file_name_input_field.config (state='disabled')
def close_window(): # exit function
window.destroy()
exit()
### CONTENTS
file_name_label = Label(window, text="File Name:")
file_name_input_field = Entry(window, width=38, borderwidth=2)
sheet_name_label = Label(window, text="Sheet Name:")
sheet_name_label_name_input_field = Entry(window, width=38, borderwidth=2)
import_button = Button(window, text="Import", padx=35, pady=0, command=import_excel_file)
search_phrase_label = Label(window, text="Search Phrase:")
search_phrase_input_field = Entry(window, width=38, borderwidth=2)
search_column_label = Label(window, text="Search Column:")
search_column_input_field = Entry(window, width=38, borderwidth=2)
offset_col_label = Label(window, text="Offset Column:")
offset_col_input_field = Entry(window, width=38, borderwidth=2)
target_col_label = Label(window, text="Target Column:")
target_col_input_field = Entry(window, width=38, borderwidth=2)
target_row_label = Label(window, text="Target Row:")
target_row_input_field = Entry(window, width=38, borderwidth=2)
new_file_label = Label(window, text="Name of New file:")
new_file_input_field = Entry(window, width=38, borderwidth=2)
define_subtotal_button = Button(window, text="Define Subtotal", padx=5, pady=0, command=define_subtotal)
execute_button = Button(window, text="Execute", padx=5, pady=0, command=execute)
# contents Column 2
status_label = Label(window, text="Status:")
output = Text(window, width=50, height=25, wrap=WORD, bg="white") # wrap=WORD : wrap text when in overflow.
output.insert(END, "Drag and drop file into project file\n"
"Define File Name and Sheet Name\n"
"Example: filename.xlsx /.xlsm/ xltx/.xltm")
exit_button = Button(window, text="exit", width=14, command=close_window)
### THE GRID
file_name_label.grid(row=0, column=0, columnspan=2, padx=0, pady=0, sticky=W)
file_name_input_field.grid(row=1, column=0, columnspan=2, padx=5, pady=3, sticky=W)
sheet_name_label.grid(row=2, column=0, columnspan=2, padx=0, pady=0, sticky=W)
sheet_name_label_name_input_field.grid(row=3, column=0, columnspan=2, padx=5, pady=3, sticky=W)
import_button.grid(row=4, column=0, columnspan=2, sticky=W, padx=5)
search_phrase_label.grid(row=5, column=0, columnspan=2, padx=0, pady=0, sticky=W)
search_phrase_input_field.grid(row=6, column=0, columnspan=2, padx=5, pady=5, sticky=W)
search_column_label.grid(row=7, column=0, columnspan=2, padx=0, pady=0, sticky=W)
search_column_input_field.grid(row=8, column=0, columnspan=2, padx=5, pady=5, sticky=W)
offset_col_label.grid(row=9, column=0, columnspan=2, padx=0, pady=0, sticky=W)
offset_col_input_field.grid(row=10, column=0, columnspan=2, padx=5, pady=5, sticky=W)
target_col_label.grid(row=11, column=0, columnspan=2, padx=0, pady=0, sticky=W)
target_col_input_field.grid(row=12, column=0, columnspan=2, padx=5, pady=5, sticky=W)
target_row_label.grid(row=13, column=0, columnspan=2, padx=0, pady=0, sticky=W)
target_row_input_field.grid(row=14, column=0, columnspan=2, padx=5, pady=5, sticky=W)
new_file_label.grid(row=15, column=0, columnspan=2, padx=0, pady=0, sticky=W)
new_file_input_field.grid(row=16, column=0, columnspan=2, padx=5, pady=5, sticky=W)
define_subtotal_button.grid(row=17, column=0, sticky=W, padx=5)
# GRID column 1
execute_button.grid(row=17, column=1, sticky=W, padx=5)
# GRID Column 2
status_label.grid(row=0, column=2, padx=5, sticky=W)
output.grid(row=1, column=2, rowspan=25, padx=5, sticky=NE)
exit_button.grid(row=17, column=2, sticky=E)
window.mainloop()
[enter image description here][1]
may be it will be a good option to use
try:
your code
except:
pass
And run your code inside of this from which you want to skip the error with this try except. if any exception happened then it will ignore this and will be running.
I have made a program where the user enter's a target number and 4 other numbers to make that target number. Right now I am having trouble to intergrate my tkinter interface to my code. So I am hoping that some one can help me
Tkinter interface:
window = Tk()
window.title("target number solution")
Label(window,image='', bg="white") .grid(row=0, column=0, sticky=W)
Label(window, text="Enter target number:",bg="black", fg="white", font="none 12 bold").grid(row=1, column=0, sticky=N)
textentry = Entry(window, width=20, bg="white")
textentry.grid(row=2, column=0, sticky=N)
Label(window, text="Enter first number:",bg="black", fg="white", font="none 12 bold").grid(row=4, column=0, sticky=N)
textentry = Entry(window, width=20, bg="white")
textentry.grid(row=5, column=0, sticky=N)
Label(window, text="Enter second number:",bg="black", fg="white", font="none 12 bold").grid(row=6, column=0, sticky=N)
textentry = Entry(window, width=20, bg="white")
textentry.grid(row=7, column=0, sticky=N)
Label(window, text="Enter third number:",bg="black", fg="white", font="none 12 bold").grid(row=8, column=0, sticky=N)
textentry = Entry(window, width=20, bg="white")
textentry.grid(row=9, column=0, sticky=N)
Label(window, text="Enter fourth number:",bg="black", fg="white", font="none 12 bold").grid(row=10, column=0, sticky=N)
textentry = Entry(window, width=20, bg="white")
textentry.grid(row=11, column=0, sticky=N)
Button(window, text="Solve", width=6, command=solver).grid(row=12, column=0, sticky=N)
output = Text(window, width=60, height=10, wrap=WORD, background="white")
output.grid(row=13, column=0, columnspan=1, sticky=N)
window.mainloop()
This is the code that needs to be linked with the tkinter interface:
from itertools import permutations,combinations_with_replacement
numbers = []
target = int(input())
operators = ["+","-","*","/"]
groups = ['X+X+X+X', 'X+X+(X+X)', 'X+(X+X)+X', '(X+X+X)+X', '(X+X)+X+X', 'X+(X+X+X)', '((X+X)+X)+X', 'X+(X+(X+X))', 'X+((X+X)+X)', '(X+X)+(X+X)', '(X+(X+X))+X']
seen = set()
for values in permutations(numbers,len(numbers)):
for operCombo in combinations_with_replacement(operators,len(numbers)-1):
for oper in permutations(operCombo,len(numbers)-1):
formulaKey = "".join(oper+values)
if formulaKey in seen: continue # ignore variations on parentheses alone
for pattern in groups:
formula = "".join(o+p for o,p in zip([""]+list(oper), pattern.split("+")))
formula = "".join(v+p for v,p in zip([""]+list(values),formula.split("X")))
try:
if eval(formula) == target:
global Answer
Answer = formula,"=",target
print(formula,"=",target)
seen.add(formulaKey)
break
except: pass
All suggestions will be grealty appriciated
You can store the values for each number in seperate IntVar variables, then get the values of these variables inside the solver function and perform all the operations that are in your second code. The code should be modularised with the use of a class containing functions that create the widgets and run the solver code. To read more about class-based declarations in Tkinter, read this.
from tkinter import Tk, Frame, Label, Button, IntVar, Entry, Text, W, N, WORD, INSERT
from itertools import permutations,combinations_with_replacement
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.target_num = IntVar()
self.num1 = IntVar()
self.num2 = IntVar()
self.num3 = IntVar()
self.num4 = IntVar()
# self.title("target number solution")
Label(self,image='', bg="white").grid(row=0, column=0, sticky=W)
Label(self, text="Enter target number:", bg="black", fg="white", font="none 12 bold").grid(row=1, column=0, sticky=N)
self.textentry1 = Entry(self, textvariable=self.target_num, width=20, bg="white")
self.textentry1.grid(row=2, column=0, sticky=N)
Label(self, text="Enter first number:",bg="black", fg="white", font="none 12 bold").grid(row=4, column=0, sticky=N)
self.textentry2 = Entry(self, textvariable=self.num1, width=20, bg="white")
self.textentry2.grid(row=5, column=0, sticky=N)
Label(self, text="Enter second number:",bg="black", fg="white", font="none 12 bold").grid(row=6, column=0, sticky=N)
self.textentry3 = Entry(self, textvariable=self.num2, width=20, bg="white")
self.textentry3.grid(row=7, column=0, sticky=N)
Label(self, text="Enter third number:",bg="black", fg="white", font="none 12 bold").grid(row=8, column=0, sticky=N)
self.textentry3 = Entry(self, textvariable=self.num3, width=20, bg="white")
self.textentry3.grid(row=9, column=0, sticky=N)
Label(self, text="Enter fourth number:",bg="black", fg="white", font="none 12 bold").grid(row=10, column=0, sticky=N)
self.textentry4 = Entry(self, textvariable=self.num4, width=20, bg="white")
self.textentry4.grid(row=11, column=0, sticky=N)
Button(self, text="Solve", width=6, command=self.solver).grid(row=12, column=0, sticky=N)
self.output = Text(self, width=60, height=10, wrap=WORD, background="white")
self.output.grid(row=13, column=0, columnspan=1, sticky=N)
def solver(self):
target = self.target_num.get()
number1 = self.num1.get()
number2 = self.num2.get()
number3 = self.num3.get()
number4 = self.num4.get()
numbers = [number1, number2, number3, number4]
operators = ["+","-","*","/"]
groups = ['X+X+X+X', 'X+X+(X+X)', 'X+(X+X)+X', '(X+X+X)+X', '(X+X)+X+X', 'X+(X+X+X)', '((X+X)+X)+X', 'X+(X+(X+X))', 'X+((X+X)+X)', '(X+X)+(X+X)', '(X+(X+X))+X']
seen = set()
for values in permutations(numbers,len(numbers)):
for operCombo in combinations_with_replacement(operators,len(numbers)-1):
for oper in permutations(operCombo,len(numbers)-1):
formulaKey = "".join(str(oper+values))
if formulaKey in seen: continue # ignore variations on parentheses alone
for pattern in groups:
formula = "".join(str(o)+str(p) for o,p in zip([""]+list(oper), pattern.split("+")))
formula = "".join(str(v)+str(p) for v,p in zip([""]+list(values),formula.split("X")))
try:
if eval(formula) == target:
Answer = formula,"=",target
print(formula,"=",target)
seen.add(formulaKey)
#insert value in output Textbox
self.output.insert(INSERT, Answer)
self.output.insert(END, '\n')
break
except: pass
root = Tk()
app = Application(master=root)
app.master.title("target number solution")
app.mainloop()
A few things that you can change/try:
Keep the "Entry" variables unique. Then extract each number using .get() command.
Use lambda in the command options of the Button as follows:
command = lambda: solver(num1, num2, num3, num4)
And if you want to display your returned number from 'solver', grid a Label in your tkinter window. Then use Label.config(text="Your number here") to show it in your tkinter window
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()