After changing the font size of the widget text increases , how to make it static?
I'm giving you all the code so you can run the program. So do not swear
from tkinter import*
import tkinter as tk
from tkinter import Toplevel, Listbox, StringVar, BooleanVar, TclError
from tkinter import filedialog, scrolledtext,Menu,END,messagebox
from tkinter.ttk import Checkbutton, Frame, Label, Button, Scrollbar, Style, Entry
from tkinter.font import families, Font
from locale import getdefaultlocale
import PIL
from PIL import Image, ImageTk
__version__ = "2.0.2"
# --- translation
EN = {"Cancel": "Cancel", "Bold": "Bold", "Italic": "Italic",
"Underline": "Underline", "Overstrike": "Strikethrough"}
FR = {"Cancel": "Annuler", "Bold": "Gras", "Italic": "Italique",
"Underline": "Souligné", "Overstrike": "Barré"}
LANGUAGES = {"fr": FR, "en": EN}
if getdefaultlocale()[0][:2] == "fr":
TR = LANGUAGES["fr"]
else:
TR = LANGUAGES["en"]
class FontChooser(Toplevel):
""".Font chooser dialog."""
def __init__(self, master, font_dict={}, text="Abcd", title="Font Chooser",
**kwargs):
"""
Create a new FontChooser instance.
Arguments:
master: master window
font_dict: dictionnary, like the one returned by the .actual
method of a Font object:
{'family': 'DejaVu Sans',
'overstrike': False,
'size': 12,
'slant': 'italic' or 'roman',
'underline': False,
'weight': 'bold' or 'normal'}
text: text to be displayed in the preview label
title: window title
**kwargs: additional keyword arguments to be passed to
Toplevel.__init__
"""
Toplevel.__init__(self, master, **kwargs)
self.title(title)
self.resizable(False, False)
self.protocol("WM_DELETE_WINDOW", self.quit)
self._validate_family = self.register(self.validate_font_family)
self._validate_size = self.register(self.validate_font_size)
# --- variable storing the chosen font
self.res = ""
style = Style(self)
style.configure("prev.TLabel", background="white")
bg = style.lookup("TLabel", "background")
self.configure(bg=bg)
# --- family list
self.fonts = list(set(families()))
self.fonts.append("TkDefaultFont")
self.fonts.sort()
for i in range(len(self.fonts)):
self.fonts[i] = self.fonts[i].replace(" ", "\ ")
max_length = int(2.5 * max([len(font) for font in self.fonts])) // 3
self.sizes = ["%i" % i for i in (list(range(6, 17)) + list(range(18, 32, 2)))]
# --- font default
font_dict["weight"] = font_dict.get("weight", "normal")
font_dict["slant"] = font_dict.get("slant", "roman")
font_dict["underline"] = font_dict.get("underline", False)
font_dict["overstrike"] = font_dict.get("overstrike", False)
font_dict["family"] = font_dict.get("family",
self.fonts[0].replace('\ ', ' '))
font_dict["size"] = font_dict.get("size", 10)
# --- creation of the widgets
# ------ style parameters (bold, italic ...)
options_frame = Frame(self, relief='groove', borderwidth=2)
self.font_family = StringVar(self, " ".join(self.fonts))
self.font_size = StringVar(self, " ".join(self.sizes))
self.var_bold = BooleanVar(self, font_dict["weight"] == "bold")
b_bold = Checkbutton(options_frame, text=TR["Bold"],
command=self.toggle_bold,
variable=self.var_bold)
b_bold.grid(row=0, sticky="w", padx=4, pady=(4, 2))
self.var_italic = BooleanVar(self, font_dict["slant"] == "italic")
b_italic = Checkbutton(options_frame, text=TR["Italic"],
command=self.toggle_italic,
variable=self.var_italic)
b_italic.grid(row=1, sticky="w", padx=4, pady=2)
self.var_underline = BooleanVar(self, font_dict["underline"])
b_underline = Checkbutton(options_frame, text=TR["Underline"],
command=self.toggle_underline,
variable=self.var_underline)
b_underline.grid(row=2, sticky="w", padx=4, pady=2)
self.var_overstrike = BooleanVar(self, font_dict["overstrike"])
b_overstrike = Checkbutton(options_frame, text=TR["Overstrike"],
variable=self.var_overstrike,
command=self.toggle_overstrike)
b_overstrike.grid(row=3, sticky="w", padx=4, pady=(2, 4))
# ------ Size and family
self.var_size = StringVar(self)
self.entry_family = Entry(self, width=max_length, validate="key",
validatecommand=(self._validate_family, "%d", "%S",
"%i", "%s", "%V"))
self.entry_size = Entry(self, width=4, validate="key",
textvariable=self.var_size,
validatecommand=(self._validate_size, "%d", "%P", "%V"))
self.list_family = Listbox(self, selectmode="browse",
listvariable=self.font_family, highlightthickness=0, exportselection=False, width=max_length)
self.list_size = Listbox(self, selectmode="browse",
listvariable=self.font_size, highlightthickness=0, exportselection=False, width=4)
scroll_family = Scrollbar(self, orient='vertical', command=self.list_family.yview)
scroll_size = Scrollbar(self, orient='vertical', command=self.list_size.yview)
self.preview_font = Font(self, **font_dict)
if len(text) > 30:
text = text[:30]
self.preview = Label(self, relief="groove", style="prev.TLabel", text=text, font=self.preview_font, anchor="center")
self.list_family.configure(yscrollcommand=scroll_family.set)
self.list_size.configure(yscrollcommand=scroll_size.set)
self.entry_family.insert(0, font_dict["family"])
self.entry_family.selection_clear()
self.entry_family.icursor("end")
self.entry_size.insert(0, font_dict["size"])
try:
i = self.fonts.index(self.entry_family.get().replace(" ", "\ "))
except ValueError:
i = 0
self.list_family.selection_clear(0, "end")
self.list_family.selection_set(i)
self.list_family.see(i)
try:
i = self.sizes.index(self.entry_size.get())
self.list_size.selection_clear(0, "end")
self.list_size.selection_set(i)
self.list_size.see(i)
except ValueError:
pass
self.entry_family.grid(row=0, column=0, sticky="ew", pady=(10, 1), padx=(10, 0))
self.entry_size.grid(row=0, column=2, sticky="ew", pady=(10, 1), padx=(10, 0))
self.list_family.grid(row=1, column=0, sticky="nsew", pady=(1, 10), padx=(10, 0))
self.list_size.grid(row=1, column=2, sticky="nsew", pady=(1, 10), padx=(10, 0))
scroll_family.grid(row=1, column=1, sticky='ns', pady=(1, 10))
scroll_size.grid(row=1, column=3, sticky='ns', pady=(1, 10))
options_frame.grid(row=0, column=4, rowspan=2, padx=10, pady=10, ipadx=10)
self.preview.grid(row=2, column=0, columnspan=5, sticky="eswn", padx=10, pady=(0, 10), ipadx=4, ipady=4)
button_frame = Frame(self)
button_frame.grid(row=3, column=0, columnspan=5, pady=(0, 10), padx=10)
Button(button_frame, text="Ok", command=self.ok).grid(row=0, column=0, padx=4, sticky='ew')
Button(button_frame, text=TR["Cancel"], command=self.quit).grid(row=0, column=1, padx=4, sticky='ew')
self.list_family.bind('<<ListboxSelect>>', self.update_entry_family)
self.list_size.bind('<<ListboxSelect>>', self.update_entry_size, add=True)
self.list_family.bind("<KeyPress>", self.keypress)
self.entry_family.bind("<Return>", self.change_font_family)
self.entry_family.bind("<Tab>", self.tab)
self.entry_size.bind("<Return>", self.change_font_size)
self.entry_family.bind("<Down>", self.down_family)
self.entry_size.bind("<Down>", self.down_size)
self.entry_family.bind("<Up>", self.up_family)
self.entry_size.bind("<Up>", self.up_size)
self.bind_class("TEntry", "<Control-a>", self.select_all)
self.wait_visibility(self)
self.grab_set()
self.entry_family.focus_set()
self.lift()
def select_all(self, event):
event.widget.selection_range(0, "end")
def keypress(self, event):
key = event.char.lower()
l = [i for i in self.fonts if i[0].lower() == key]
if l:
i = self.fonts.index(l[0])
self.list_family.selection_clear(0, "end")
self.list_family.selection_set(i)
self.list_family.see(i)
self.update_entry_family()
def up_family(self, event):
try:
i = self.list_family.curselection()[0]
self.list_family.selection_clear(0, "end")
if i <= 0:
i = len(self.fonts)
self.list_family.see(i - 1)
self.list_family.select_set(i - 1)
except TclError:
self.list_family.selection_clear(0, "end")
i = len(self.fonts)
self.list_family.see(i - 1)
self.list_family.select_set(i - 1)
self.list_family.event_generate('<<ListboxSelect>>')
def up_size(self, event):
"""Navigate in the size listbox with up key."""
try:
s = self.var_size.get()
if s in self.sizes:
i = self.sizes.index(s)
elif s:
sizes = list(self.sizes)
sizes.append(s)
sizes.sort(key=lambda x: int(x))
i = sizes.index(s)
else:
i = 0
self.list_size.selection_clear(0, "end")
if i <= 0:
i = len(self.sizes)
self.list_size.see(i - 1)
self.list_size.select_set(i - 1)
except TclError:
i = len(self.sizes)
self.list_size.see(i - 1)
self.list_size.select_set(i - 1)
self.list_size.event_generate('<<ListboxSelect>>')
def down_family(self, event):
"""Navigate in the family listbox with down key."""
try:
i = self.list_family.curselection()[0]
self.list_family.selection_clear(0, "end")
if i >= len(self.fonts):
i = -1
self.list_family.see(i + 1)
self.list_family.select_set(i + 1)
except TclError:
self.list_family.selection_clear(0, "end")
self.list_family.see(0)
self.list_family.select_set(0)
self.list_family.event_generate('<<ListboxSelect>>')
def down_size(self, event):
"""Navigate in the size listbox with down key."""
try:
s = self.var_size.get()
if s in self.sizes:
i = self.sizes.index(s)
elif s:
sizes = list(self.sizes)
sizes.append(s)
sizes.sort(key=lambda x: int(x))
i = sizes.index(s) - 1
else:
s = len(self.sizes) - 1
self.list_size.selection_clear(0, "end")
if i < len(self.sizes) - 1:
self.list_size.selection_set(i + 1)
self.list_size.see(i + 1)
else:
self.list_size.see(0)
self.list_size.select_set(0)
except TclError:
self.list_size.selection_set(0)
self.list_size.event_generate('<<ListboxSelect>>')
def toggle_bold(self):
"""Update font preview weight."""
b = self.var_bold.get()
self.preview_font.configure(weight=["normal", "bold"][b])
def toggle_italic(self):
"""Update font preview slant."""
b = self.var_italic.get()
self.preview_font.configure(slant=["roman", "italic"][b])
def toggle_underline(self):
"""Update font preview underline."""
b = self.var_underline.get()
self.preview_font.configure(underline=b)
def toggle_overstrike(self):
"""Update font preview overstrike."""
b = self.var_overstrike.get()
self.preview_font.configure(overstrike=b)
def change_font_family(self, event=None):
"""Update font preview family."""
family = self.entry_family.get()
if family.replace(" ", "\ ") in self.fonts:
self.preview_font.configure(family=family)
def change_font_size(self, event=None):
"""Update font preview size."""
size = int(self.var_size.get())
self.preview_font.configure(size=size)
def validate_font_size(self, d, ch, V):
"""Validation of the size entry content."""
l = [i for i in self.sizes if i[:len(ch)] == ch]
i = None
if l:
i = self.sizes.index(l[0])
elif ch.isdigit():
sizes = list(self.sizes)
sizes.append(ch)
sizes.sort(key=lambda x: int(x))
i = min(sizes.index(ch), len(self.sizes))
if i is not None:
self.list_size.selection_clear(0, "end")
self.list_size.selection_set(i)
deb = self.list_size.nearest(0)
fin = self.list_size.nearest(self.list_size.winfo_height())
if V != "forced":
if i < deb or i > fin:
self.list_size.see(i)
return True
if d == '1':
return ch.isdigit()
else:
return True
def tab(self, event):
"""Move at the end of selected text on tab press."""
self.entry_family = event.widget
self.entry_family.selection_clear()
self.entry_family.icursor("end")
return "break"
def validate_font_family(self, action, modif, pos, prev_txt, V):
"""Completion of the text in the entry with existing font names."""
if self.entry_family.selection_present():
sel = self.entry_family.selection_get()
txt = prev_txt.replace(sel, '')
else:
txt = prev_txt
if action == "0":
txt = txt[:int(pos)] + txt[int(pos) + 1:]
return True
else:
txt = txt[:int(pos)] + modif + txt[int(pos):]
ch = txt.replace(" ", "\ ")
l = [i for i in self.fonts if i[:len(ch)] == ch]
if l:
i = self.fonts.index(l[0])
self.list_family.selection_clear(0, "end")
self.list_family.selection_set(i)
deb = self.list_family.nearest(0)
fin = self.list_family.nearest(self.list_family.winfo_height())
index = self.entry_family.index("insert")
self.entry_family.delete(0, "end")
self.entry_family.insert(0, l[0].replace("\ ", " "))
self.entry_family.selection_range(index + 1, "end")
self.entry_family.icursor(index + 1)
if V != "forced":
if i < deb or i > fin:
self.list_family.see(i)
return True
else:
return False
def update_entry_family(self, event=None):
"""Update family entry when an item is selected in the family listbox."""
# family = self.list_family.get("#%i,%i" % (event.x , event.y))
family = self.list_family.get(self.list_family.curselection()[0])
self.entry_family.delete(0, "end")
self.entry_family.insert(0, family)
self.entry_family.selection_clear()
self.entry_family.icursor("end")
self.change_font_family()
def update_entry_size(self, event):
"""Update size entry when an item is selected in the size listbox."""
# size = self.list_size.get("#%i,%i" % (event.x , event.y))
size = self.list_size.get(self.list_size.curselection()[0])
self.var_size.set(size)
self.change_font_size()
def ok(self):
"""Validate choice."""
self.res = self.preview_font.actual()
self.quit()
def get_res(self):
"""Return chosen font."""
return self.res
def quit(self):
self.destroy()
def askfont(master=None, text="Abcd", title="Font Chooser", **font_args):
chooser = FontChooser(master, font_args, text, title)
chooser.wait_window(chooser)
return chooser.get_res()
def edit_font():
font = askfont(root, title="Choose a font")
if font:
font['family'] = font['family'].replace(' ', '\ ')
font_str = "%(family)s %(size)i %(weight)s %(slant)s" % font
if font['underline']:
font_str += ' underline'
if font['overstrike']:
font_str += ' overstrike'
text.configure(font=font_str)
root=tk.Tk()
root.geometry("1423x800")
# added weights so the widget resizes correctly with window
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
image = ImageTk.PhotoImage(file="0.png")
lab=tk.Label(root, image = image)
lab.grid(row=0, column=0)
text=tk.Text(root,width = 60,height=15, font=Font(family="Helvetica", size=10))
text.grid(row=0, column=0)
king=tk.Menu(root)
root.config(menu=king)
view=tk.Menu(king, tearoff=0)
view2=tk.Menu(view, tearoff=0)
view2.add_command(label='Font',command=edit_font)
view.add_cascade(label='Text', menu=view2)
king.add_cascade(label='View', menu=view)
root.mainloop()
This is the code you will most likely need to fix my problem:
def askfont(master=None, text="Abcd", title="Font Chooser", **font_args):
chooser = FontChooser(master, font_args, text, title)
chooser.wait_window(chooser)
return chooser.get_res()
def edit_font():
font = askfont(root, title="Choose a font")
if font:
font['family'] = font['family'].replace(' ', '\ ')
font_str = "%(family)s %(size)i %(weight)s %(slant)s" % font
if font['underline']:
font_str += ' underline'
if font['overstrike']:
font_str += ' overstrike'
text.configure(font=font_str)
root=tk.Tk()
root.geometry("1423x800")
# added weights so the widget resizes correctly with window
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
image = ImageTk.PhotoImage(file="0.png")
lab=tk.Label(root, image = image)
lab.grid(row=0, column=0)
text=tk.Text(root,width = 60,height=15, font=Font(family="Helvetica", size=10))
text.grid(row=0, column=0)
king=tk.Menu(root)
root.config(menu=king)
view=tk.Menu(king, tearoff=0)
view2=tk.Menu(view, tearoff=0)
view2.add_command(label='Font',command=edit_font)
view.add_cascade(label='Text', menu=view2)
king.add_cascade(label='View', menu=view)
root.mainloop()
This will probably include setting the frame size and frame, as well as banning distribution, one of my friends said. Hope this helps you
If you give the Text widget a fixed height and width and wrap it in a Frame with the same width and height and use grid_propagate(False), when the text is made bigger the Text widget stays the same size.
import tkinter as tk
def fontUp():
text.config(font = ("30"))
root = tk.Tk()
root.geometry("800x800")
frm = tk.Frame(root, height = 500, width = 500)
frm.grid(row = 0, column = 0)
frm.grid_propagate(False)
text = tk.Text(frm, height = 500, width = 500)
text.grid(row = 0, column = 0)
btn = tk.Button(root, text="Font bigger", command = fontUp)
btn.grid(row = 2, column = 0)
Related
I have a python GUI assignment in which I have to create a GUI application which will evaluate a single variable function within a specified range of input values. We have to use classes. I have written the following code:
from tkinter import *
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
import tkinter.font as font
class eval_interface:
def __init__(self):
self.root = Tk()
self.root.title("Function Evaluator")
self.topframe = Frame(self.root)
self.createTopFrame()
self.topframe.grid(row=0, column=0, columnspan=10, sticky=N + S + W + E)
self.frame2 = Frame(self.root)
self.createFrame2()
self.frame2.grid(row = 1, column = 0, pady = 15, columnspan = 10, sticky = N + S + W + E)
self.frame3 = Frame(self.root)
self.createFrame3()
self.frame3.grid(row=2, column=0, pady=15, columnspan=10, sticky=N + S + W + E)
self.frame4 = Frame(self.root)
self.frame5 = Frame(self.root)
self.createFrame5()
self.frame5.grid(row=4, column=0, pady=15, columnspan=10, sticky=N + S + E + W)
self.createFrame4()
self.frame4.grid(row = 3, column = 0, pady = 15, columnspan = 10, sticky = N+S+E+W)
self.root.mainloop()
def createTopFrame(self): #Frame containing title
title = Label(self.topframe, text="Function evaluator and plotter".center(228, " "), font=font.Font(size=17))
title.grid(row=0, column=0, columnspan=7)
def createFrame2(self): #Frame containing function Entry widget
title = Label(self.frame2, text = "Enter the function in x : ", font = font.Font(size = 14))
title.grid(row = 0, column = 0, sticky = N + S + W + E)
function_entry = Entry(self.frame2, width = 150)
function_entry.grid(row = 0, column = 1, sticky = N + S + W + E)
def createFrame3(self): #Frame containing range Entry widgets
range_label = Label(self.frame3, text="Enter the range of the function from : ", font = font.Font(size = 14))
lower_range_entry = Entry(self.frame3, width=10)
range_label2 = Label(self.frame3, text=" to ")
upper_range_entry = Entry(self.frame3, width=10)
range_label.grid(row=1, column=0, sticky="nsew")
lower_range_entry.grid(row=1, column=1)
range_label2.grid(row=1, column=2, sticky="nsew")
upper_range_entry.grid(row=1, column=3, sticky="nsew")
def createFrame4(self): #Frame containing button widgets
btn_evaluate = Button(self.frame4, text = "Evaluate", font = font.Font(size = 14), command = self.evaluate())
btn_plot = Button(self.frame4, text = "Plot", font = font.Font(size = 14))
btn_clear = Button(self.frame4, text = "Clear", font = font.Font(size = 14))
btn_exit = Button(self.frame4, text = "Exit", font = font.Font(size = 14), command = exit)
btn_evaluate.grid(row=0, column=0, padx=10, pady=5)
btn_plot.grid(row=0, column=1, padx=10, pady=5)
btn_clear.grid(row=0, column=2, padx=10, pady=5)
btn_exit.grid(row=0, column=3, padx=10, pady=5)
def createFrame5(self): #Frame containing Result Textbox
res_text = Text(self.frame5, width = 95, height = 55, padx = 10)
res_text.grid(row = 0, column = 0)
def evaluate(self):
x = 10
def clear(self):
z=12
eval_interface()
My question is, how do I access the data inputted by the user in the three entry widgets (in frames 2 and 3) when the Evaluate button is clicked? And after I have accessed the data and done the necessary operations on it, how do I display the result in the Textbox in Frame 5? (I have just coded some random statement in evaluate and clear functions for now to see the output GUI.)
If you want to access the Entry widgets inside evaluate() function, you need to change the three local variables function_entry, lower_range_entry and upper_range_entry to instance variables self.function_entry, self.lower_range_entry and self.upper_range_entry. Same for the Text widget res_text. Then you can get the values from the three Entry widgets and insert the result into self.res_text inside evaluate() function:
def createFrame2(self): #Frame containing function Entry widget
title = Label(self.frame2, text = "Enter the function in x : ", font = font.Font(size = 14))
title.grid(row = 0, column = 0, sticky = N + S + W + E)
self.function_entry = Entry(self.frame2, width = 150)
self.function_entry.grid(row = 0, column = 1, sticky = N + S + W + E)
def createFrame3(self): #Frame containing range Entry widgets
range_label = Label(self.frame3, text="Enter the range of the function from : ", font = font.Font(size = 14))
self.lower_range_entry = Entry(self.frame3, width=10)
range_label2 = Label(self.frame3, text=" to ")
self.upper_range_entry = Entry(self.frame3, width=10)
range_label.grid(row=1, column=0, sticky="nsew")
self.lower_range_entry.grid(row=1, column=1)
range_label2.grid(row=1, column=2, sticky="nsew")
self.upper_range_entry.grid(row=1, column=3, sticky="nsew")
...
def createFrame5(self): #Frame containing Result Textbox
self.res_text = Text(self.frame5, width = 95, height = 55, padx = 10)
self.res_text.grid(row = 0, column = 0)
def evaluate(self):
# get content from entries
x = self.function_entry.get()
lower = self.lower_range_entry.get()
upper = self.upper_range_entry.get()
# example on inserting result into text box
result = ", ".join([x, lower, upper]) # or whatever you want
self.res_text.insert("end", result)
...
Also command=self.evaluate() inside createFrame4() should be command=self.evaluate instead.
Sorry for the mess
so I am making a seating chart, and I cant seem to get it working properly... again. I am trying to make the label reset every time i press the run button, any ideas?
#commands: add name , Run
#imports
import random
from time import sleep
from tkinter import *
#Console and background Handlers
Tables = 6
Names = []
def AddNames():
NewNames = e.get("1.0", 'end -1c')
if NewNames in Names:
print("Name Already exists")
elif NewNames == "":
print("Empty")
else:
Names.append(NewNames)
print(Names)
e.delete(1.0, END)
def Random():
RandomNum = random.randrange(Tables)
if RandomNum == 0:
RandomNum = random.randrange(Tables)
return RandomNum
def run():
X = 0
for i in Names:
#print(Names[X])
print("Table: " + str(Random()))
X += 1
#text = Label(popup, text = "")
text = Label(popup, text= Names[X] + "\n" + "Table: " + str(Random()))
text.pack()
#GUI Handler
root = Tk()
root.geometry("1024x768")
e = Text(root, bd = 10, font=("Comic Sans MS", 50) ,width = 15, height = 2)
e.pack()
popup = Toplevel()
popup.title("Seating Chart")
AddNameButton = Button(root, text = ("Add Name"), width = 15, height = 5, command = AddNames)
AddNameButton.pack()
RunButton = Button(root, text = ("Run"), width = 15, height = 5, command = run)
RunButton.pack()
root.mainloop()
I am trying to reset text every time the user presses the run button
import tkinter
from tkinter import ttk
import random
class MyApp:
def __init__(self):
self.root = tkinter.Tk()
self.seatwindow = None
self.root.title('Add Names')
self.currentname = tkinter.StringVar()
self._maxtables = tkinter.StringVar()
self.addednames = []
self.commandframe = ttk.Labelframe(self.root, text='Commands')
self.nameentry = ttk.Entry(self.root, textvariable=self.currentname)
self.addbutton = ttk.Button(self.root, text='Add Name', command=self.addname)
self.maxtablabel = ttk.Label(self.root, text='Tables: ')
self.maxtabentry = ttk.Entry(self.root, textvariable=self._maxtables)
self.genbutton = ttk.Button(self.commandframe, text='Run', command=self.generate)
self.resetbutton = ttk.Button(self.commandframe, text='Reset', command=self.reset)
self._maxtables.set('6')
self.nameentry.grid(row=0, column=0)
self.addbutton.grid(row=0, column=1, sticky='nsew')
self.maxtabentry.grid(row=1, column=1, sticky='nsw')
self.maxtablabel.grid(row=1, column=0, sticky='nse')
self.genbutton.grid(row=0, column=0, sticky='nsew')
self.resetbutton.grid(row=0, column=1, sticky='nsew')
self.commandframe.grid(row=2, column=0, columnspan=2, sticky='nsew')
self.nameentry.bind('<Return>', self.addname)
self.root.bind('<Control-Return>', self.generate)
def addname(self, event=None):
name = self.currentname.get()
if not(name == '' or name in self.addednames):
self.addednames.append(name)
self.currentname.set('')
else:
self.currentname.set('Name already added!')
def generate(self, event=None):
if not self.seatwindow == None:
self.seatwindow.destroy()
self.currentname.set('')
self.seatwindow = tkinter.Toplevel()
random.shuffle(self.addednames)
tables = []
for i in range(self.maxtables):
tableframe = ttk.Labelframe(self.seatwindow, text='Table ' + str(i + 1) + ':')
tableframe.grid(column=i, row=0, sticky='nsew')
tables.append(tableframe)
for index, name in enumerate(self.addednames):
namelabel = ttk.Label(tables[index%self.maxtables], text=name)
namelabel.grid(column=0, row=index//self.maxtables + 1)
def reset(self):
self.currentname.set('')
self.maxtables = 6
self.addednames = []
def run(self):
self.root.mainloop()
#property
def maxtables(self):
return int(self._maxtables.get())
MyApp().run()
I've got a script in python2.7 write in Pycharm IDE on windows, can I run same program in ubuntu ?
from Tkinter import *
import tkFileDialog
from PIL import Image, ImageTk
class App:
label_rgb_template = "R: {0}, G: {1}, B: {2}"
def __init__(self):
self.picked_image_filename = None
self.image = None
self.tk_image = None
self.image_id = None
self.image_filename = None
self.current_size = None
self.current_factor = None
self.root = root = Tk()
self.offset_x = 0
self.offset_y = 0
root.title('Biomteria')
root.size = (500, 500)
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
root.bind("<Configure>", self.resize_handler)
root.bind("<Key>", self.root_key_press_handler)
frame = Frame(root)
frame.grid(column=0, row=0, sticky=N + S + W + E)
frame.grid_columnconfigure(10, weight=1)
btn_open = Button(frame, text='otworz plik', command=self.open_image)
btn_save = Button(frame, text='zapisz plik', command=self.save_image)
btn_zoom_in = Button(frame, text='+', command=self.zoom_in)
btn_zoom_out = Button(frame, text='-', command=self.zoom_out)
self.entry_red = entry_red = Spinbox(frame, from_=0, to=255)
label_entry_red = Label(frame, text="R:")
self.entry_green = entry_green = Spinbox(frame, from_=0, to=255)
label_entry_green = Label(frame, text="G:")
self.entry_blue = entry_blue = Spinbox(frame, from_=0, to=255)
label_entry_blue = Label(frame, text="B:")
self.label_rgb_text = StringVar()
self.label_rgb_text.set(self.label_rgb_template.format(0, 0, 0))
label_rgb = Label(frame, textvariable=self.label_rgb_text)
btn_open.grid(row=0, column=0)
btn_save.grid(row=0, column=1)
btn_zoom_in.grid(row=0, column=2)
btn_zoom_out.grid(row=0, column=3)
label_entry_red.grid(row=0, column=4)
entry_red.grid(row=0, column=5)
label_entry_green.grid(row=0, column=6)
entry_green.grid(row=0, column=7)
label_entry_blue.grid(row=0, column=8)
entry_blue.grid(row=0, column=9)
label_rgb.grid(row=0, column=10, sticky=E)
self.canvas = canvas = Canvas(root)
canvas.grid(row=1, column=0, sticky=N + S + W + E)
canvas.bind("<Button-1>", self.canvas_click_handler)
canvas.bind("<Motion>", self.canvas_motion_handler)
self.root.mainloop()
def open_image(self):
self.image_filename = image_filename = tkFileDialog.askopenfilename(filetypes=(('All files', '*.*'),))
self.image = Image.open(image_filename)
self.image = self.image.convert("RGB")
self.current_size = self.image.size
self.current_factor = 1
self.refresh()
def save_image(self):
image_filename = tkFileDialog.asksaveasfilename(initialfile=self.image_filename)
self.image.save(image_filename)
def zoom(self, factor):
self.current_size = tuple((int(value * factor) for value in self.current_size))
self.current_factor = int(self.current_factor * factor)
self.refresh()
def zoom_in(self):
self.zoom(2)
def zoom_out(self):
self.zoom(0.5)
def refresh(self):
center = (self.canvas.winfo_width() / 2 + self.offset_x, self.canvas.winfo_height() / 2 + self.offset_y)
self.canvas.delete(self.image_id)
self.tk_image = ImageTk.PhotoImage(self.image.resize(self.current_size))
self.image_id = self.canvas.create_image(center, image=self.tk_image)
def resize_handler(self, evt):
if self.image:
self.refresh()
def get_pixel_coords(self, evt):
bbox = self.canvas.bbox(ALL)
if bbox and bbox[0] <= evt.x <= bbox[2] and bbox[1] <= evt.y < bbox[3]:
pixel_coords = evt.x - bbox[0], evt.y - bbox[1]
return tuple((value / self.current_factor for value in pixel_coords))
return None
def canvas_click_handler(self, evt):
pixel_coords = self.get_pixel_coords(evt)
if pixel_coords:
color = self.entry_red.get(), self.entry_green.get(), self.entry_blue.get()
color = tuple(int(value) for value in color)
self.image.putpixel(pixel_coords, color)
self.refresh()
def canvas_motion_handler(self, evt):
pixel_coords = self.get_pixel_coords(evt)
if pixel_coords:
self.label_rgb_text.set(self.label_rgb_template.format(*self.image.getpixel(pixel_coords)))
def root_key_press_handler(self, evt):
code = evt.keycode
print code
if code == 37:
self.offset_x -= 10
if code == 38:
self.offset_y -=10
if code == 39:
self.offset_x += 10
if code == 40:
self.offset_y += 10
self.refresh()
I have to change something ?, becouse when I runing that script on ubuntu a script window opens, but buttons doesn't work
If this is all of your code, you're forgetting to create an instance of App. Add the following to the bottom of the file:
if __name__ == "__main__":
app = App()
I am attempting to write a python program that utilizes Tkinter window switching OOP classes. On the starting page, there is an entry form where the user fills in the relevant fields. After filling the form the button 'to tests' is clicked where the user can select the test after switching frame/window, and the user information entered is simultaneously saved in the specified directory as a .txt file as a result of this button running several methods in class Startpage. The problem occurs when data is received by clicking on the yes or no buttons in the test 1 page.
This page operates in a different class, yet requires a return value from method get_info() defined in the Startpage class to get the user information (filename) entered to create a second .txt file to store raw data, storing appended 'yes' or 'no' strings depending on the button clicked in test 1's GUI window.
However this file is never created since Test1 is not receiving any entry data from Startpage class/window, therefore cannot assign a filename (call the get_info() containing the widget.get() functions) for the second .txt file.
The information is obtained in by the methods in the class correctly and everything works fine. However the problem arises when Test1 asks to receive the widget.get() variables/methods from Startpage.
The error thrown is the following IndexError:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Rylan\Anaconda\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args)
File "C:/Users/Rylan/Documents/Python/Basel Summerintern files/code to help with question.py", line 280, in update_countyes
directory = "C:\Users\Rylan\Documents\Python\Basel Summerintern files\{}".format(self.get_t_info())
File "C:/Users/Rylan/Documents/Python/Basel Summerintern files/code to help with question.py", line 304, in get_t_info
self.gettheinfo = Startpage(app, self.controller).get_info()
File "C:/Users/Rylan/Documents/Python/Basel Summerintern files/code to help with question.py", line 170, in get_info
str(Day) + "_" + str(Month) + "_" +
IndexError: string index out of range
I am very new to OOP programming and to my knowledge this could be caused by:
Not properly referring/calling the Startpage instance, therefore the variables are not received by the Test1, therefore calling the get_info() method results in with nothing received by the nested widget.get() functions/variables in get_info() method.
Basically, what is the reason for this IndexError and how do I fix it to get the filename created/returned from the get_info() method in class Startpage sent to/called by class Test1?
I have seen similar questions relating to class variable and method calling from a different class, however none of which consider the case for window/frame switching Tkinter applications.
Here is the simplified code below (might not seem like it) which is able to be run (you may have directory path existence issues, just change path to whatever can be easily located for you to save the .txt files)
import Tkinter as tk
import ttk
import os
LARGE_FONT = ("Verdana", 12)
NORM_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 8)
def center(win):
"""
centers a tkinter window
param win: the window to center on the screen
"""
win.update_idletasks()
width = win.winfo_width()
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = win.winfo_height()
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
win.deiconify()
def popupmsg(msg):
popup1 = tk.Tk()
center(popup1)
popup1.minsize(width=60, height=70)
popup1.maxsize(width=60, height=70)
popup1.wm_title("Attention!")
label = ttk.Label(popup1, text=msg, font=NORM_FONT, anchor="center")
label.pack(side="top", fill="x", pady=10)
b1 = ttk.Button(popup1, text="Ok", command=lambda: popup1.destroy())
b1.pack()
popup1.mainloop()
class Testapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.iconbitmap(self, default="testappicon2.ico")
tk.Tk.wm_title(self, "Psychoacoustic Tests")
container = ttk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_columnconfigure(0, weight=1)
container.grid_rowconfigure(0, weight=1)
menubar = tk.Menu(container)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=lambda: self.destroy())
menubar.add_cascade(label="File", menu=filemenu)
tk.Tk.config(self, menu=menubar)
self.frames = {}
for F in (Startpage, TestSelect, Test1):
frame = F(container, self)
self.frames[F] = frame
self.minsize(width=900, height=500)
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(Startpage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class Startpage(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
self.controller = controller
self.titlelabel = ttk.Label(self, text="User Information", font = LARGE_FONT)
self.titlelabel.grid(row=0, column=0, columnspan=4, padx = 10, pady = 10)
self.firstnamelabel = ttk.Label(self, text="First Name: ", font = NORM_FONT)
self.firstnamelabel.grid(row=1, column=0, sticky = 'w', padx = 15, pady = 10)
self.lastnamelabel = ttk.Label(self, text="Last Name: ", font = NORM_FONT)
self.lastnamelabel.grid(row=2, column=0, sticky = 'w', padx = 15, pady = 10)
self.firstnameentry = ttk.Entry(self)
self.firstnameentry.grid(row=1, column=1, padx=5, sticky = 'we', columnspan = 3)
self.lastnameentry = ttk.Entry(self)
self.lastnameentry.grid(row=2, column=1, padx=5, sticky = 'we', columnspan = 3)
self.birthdaylabel = ttk.Label(self, text="Birthday: ", font = NORM_FONT)
self.birthdaylabel.grid(row=3, column=0, sticky = 'w', padx = 15, pady = 10)
self.daydropdown = ttk.Combobox(self, justify='center', height=20, width=2,
values = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,
15,16,17,18,19,20,21,22,23,24,25,
26,27,28,29,30,31),
state='readonly')
self.daydropdown.grid(row=3, column=1, padx = 3, sticky = 'ew')
self.monthdropdown = ttk.Combobox(self, justify='center', height=12, width=10,
values = ('January','Feburary','March',
'April','May','June','July',
'August','September','October',
'November','December'),
state='readonly')
self.monthdropdown.grid(row=3, column=2, padx=3, sticky = 'ew')
self.yeardropdown = ttk.Combobox(self, justify='center', height=20, width=4,
values = (1980, 1981, 1982, 1983, 1984,
1985, 1986, 1987, 1988, 1989,
1990, 1991, 1992, 1993, 1994,
1995, 1996, 1997, 1998, 1999),
state = 'readonly')
self.yeardropdown.grid(row=3, column=3, padx = 3, sticky = 'ew')
self.genderlabel = ttk.Label(self, text="Gender: ", font = NORM_FONT)
self.genderlabel.grid(row=4, column=0, sticky = 'w', padx = 15, pady = 10)
self.var = tk.IntVar()
self.Maleradio = ttk.Radiobutton(self, text='Male', variable=self.var, value = 1)
self.Maleradio.grid(row=4, column=1, sticky = 'w')
self.Femaleradio = ttk.Radiobutton(self, text='Female', variable=self.var, value = 2)
self.Femaleradio.grid(row=5, column=1, sticky = 'w')
self.emaillabel = ttk.Label(self, text="Email: ", font = NORM_FONT)
self.emaillabel.grid(row=6, column=0, sticky = 'w', padx = 15, pady = 10)
self.emailentry = ttk.Entry(self)
self.emailentry.grid(row=6, column=1, columnspan=3, sticky='ew')
self.experiencelabel = ttk.Label(self, text="Musical Experience: ", font = NORM_FONT)
self.experiencelabel.grid(row=7, column=0, sticky = 'w', padx = 15, pady = 10)
self.expdropdown = ttk.Combobox(self, justify='center', height=3, width=17,
values = ('No experience', 'Some experience',
'Musician level'), state='readonly')
self.expdropdown.grid(row=7, column=1, columnspan=3, sticky = 'w')
self.button1 = ttk.Button(self, text="To Tests", command= lambda: self.checkempty())
self.button1.grid(row=8, column=3)
def shortcut():
controller.show_frame(TestSelect)
buttonshort = ttk.Button(self, text="To Tests shortcut", command= lambda: shortcut())
buttonshort.grid(row=9, column=3)
def get_info(self):
Name = self.firstnameentry.get()
Surname = self.lastnameentry.get()
Day = self.daydropdown.get()
Month = self.monthdropdown.get()
Year = self.yeardropdown.get()
foldername = (str(Name[0]) + str(Surname[0]) +
str(Day) + "_" + str(Month) + "_" +
str(Year))
return foldername
def create_directory(self):
if not os.path.isdir(self.get_info()):
directory = "C:\Users\Rylan\Documents\Python\Basel Summerintern files\{}".format(self.get_info())
os.makedirs(directory)
datafile = "{}_userinfo.txt".format(self.get_info())
entirefile = os.path.join(directory, datafile)
myfile = open(entirefile, 'w')
myfile.write(self.userinfo())
myfile.close()
self.controller.show_frame(TestSelect)
else:
popupmsg("Folder already exists")
def userinfo(self):
Name = self.firstnameentry.get()
Surname = self.lastnameentry.get()
Day = self.daydropdown.get()
Month = self.monthdropdown.get()
Year = self.yeardropdown.get()
Email = self.emailentry.get()
Experience = self.expdropdown.get()
def genderget():
Gender = self.var.get()
if Gender == 1:
UserGender = "Male"
elif Gender == 2:
UserGender = "Female"
return UserGender
user_info = ("Participant Name: " + str(Name) + " " +
str(Surname) + "\nBirthday: " + str(Day) + "_" +
str(Month) + "_" + str(Year) + "\nGender: " +
str(genderget()) + "\nEmail: " + str(Email) +
"\nMusical Experience: " + str(Experience) +
"\nDirectory Name: " + str(self.get_info()))
return user_info
def checkempty(self):
Name = self.firstnameentry.get()
Surname = self.lastnameentry.get()
Day = self.daydropdown.get()
Month = self.monthdropdown.get()
Year = self.yeardropdown.get()
Email = self.emailentry.get()
Experience = self.expdropdown.get()
if len(Name) == 0:
popupmsg("Please complete the user information form")
elif len(Surname) == 0:
popupmsg("Please complete the user information form")
elif Day == None:
popupmsg("Please complete the user information form")
elif Month == None:
popupmsg("Please complete the user information form")
elif Year == None:
popupmsg("Please complete the user information form")
elif self.var.get() == 0:
popupmsg("Please complete the user information form")
elif len(Email) == 0:
popupmsg("Please complete the user information form")
elif Experience == None:
popupmsg("Please complete the user information form")
else:
self.create_directory()
class TestSelect(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
self.controller = controller
label = ttk.Label(self, text="Select tests", font = LARGE_FONT)
label.grid(row=0, column=0, columnspan=3)
Test1Button = ttk.Button(self, text="Do test 1", command=lambda: controller.show_frame(Test1))
Test1Button.grid(row=1, column=0, padx = 20, pady = 15, sticky = 'nsew')
button2 = ttk.Button(self, text="Home", command=lambda: controller.show_frame(Startpage))
button2.grid(row=3, column=2)
class Test1(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
self.controller = controller
label = ttk.Label(self, text="Test 1", font = LARGE_FONT)
label.grid(row=0, column=0, columnspan=2)
button2 = ttk.Button(self, text="Page one", command=lambda: controller.show_frame(TestSelect))
button2.grid(row=1, column=0, sticky = "w")
yesbutt1 = ttk.Button(self)
yesbutt1.grid(row=2, column=0)
nobutt1 = ttk.Button(self)
nobutt1.grid(row=2, column=1)
yesbutt1['text'] = "Yes: 0"
nobutt1['text'] = "No: 0"
self.nobttn_clicks = 0
self.yesbttn_clicks = 0
def update_countyes():
if self.yesbttn_clicks >= 1 or self.nobttn_clicks >= 1:
popupmsg("Only one answer allowed!")
else:
self.yesbttn_clicks += 1
yesbutt1['text'] = "Yes: " + str(self.yesbttn_clicks)
directory = "C:\Users\Rylan\Documents\Python\Basel Summerintern files\{}".format(self.get_t_info())
datafile = "{}_test1data.txt".format(self.get_t_info())
entirefile = os.path.join(directory, datafile)
myfile = open(entirefile, 'a')
myfile.write('\nyes')
myfile.close()
def update_countno():
if self.yesbttn_clicks >= 1 or self.nobttn_clicks >= 1:
popupmsg("Only one answer allowed!")
else:
self.nobttn_clicks += 1
nobutt1['text'] = "No: " + str(self.nobttn_clicks)
directory = "C:\Users\Rylan\Documents\Python\Basel Summerintern files\{}".format(self.get_t_info())
datafile = "{}_test1data.txt".format(self.get_t_info())
entirefile = os.path.join(directory, datafile)
myfile = open(entirefile, 'a')
myfile.write('\nno')
myfile.close()
yesbutt1['command'] = update_countyes
nobutt1['command'] = update_countno
def get_t_info(self):
self.gettheinfo = Startpage(app, self.controller).get_info()
return self.gettheinfo
app = Testapp()
app.mainloop()
Your problem is that when you write:
def get_t_info(self):
self.gettheinfo = Startpage(app, self.controller).get_info()
return self.gettheinfo
you create a new StartPage where the Entries are empty.
Then
Name = self.firstnameentry.get()
...
foldername = (str(Name[0])
tries to get the first character of an empty string.
I think the solution should be something like:
def get_t_info(self):
return self.controller.frames[Startpage]
I tried this:
self.btnquit = button(calc_frame, "Quit", tk.destroy)
self.btnquit.pack(side = LEFT)
before self.input = ...
But it came out invalid syntax. And the backspace only works if its in front of the number but I want it to be able to ackspace the last number entered, clear the last equation and then:
from tkinter import *
from tkinter.font import Font
def button(frame, text, command=None):
ft = Font(family=('Verdana'), size=14)
return Button(frame, text=text, font=ft, width=3, command=command)
def frame(frame, side=LEFT, bg="black"):
f = Frame(frame, background=bg, padx=5, pady=5)
f.pack(side=side, expand=YES, fill=BOTH)
return f
class App:
def __init__(self, tk):
ft = Font(family=('Verdana'), size=14)
main = frame(tk)
l_frame = frame(main)
r_frame = frame(main)
calc_frame = frame(l_frame)
self.input = Entry(calc_frame, font=ft, width=15, background="white")
self.input.pack(side=TOP)
self.btn_frame = frame(calc_frame)
x, y = 0, 0
for key in ("()%C", "+-*/", "1234", "5678", "90.="):
for c in key:
if c == "=":
btn = button(self.btn_frame, c, self.equalAction)
elif c == "C":
btn = button(self.btn_frame, c, self.cleanAction)
else:
btn = button(self.btn_frame, c, lambda i=c: self.input.insert(INSERT, i))
btn.grid(row=x, column=y)
y += 1
x += 1
y = 0
self.log = Text(r_frame, font=Font(family=('Verdana'), size=10), width=25, height=14, background="yellow")
self.log.pack(side=RIGHT)
def cleanAction(self):
self.input.delete(0, END)
def equalAction(self):
tmp = self.input.get()
try:
result = tmp + "=" + str(eval(tmp))
self.log.insert(1.0, result + "\n");
print(result)
except Exception:
self.log.insert(1.0, "Wrong expression\n");
if __name__ == '__main__':
root = Tk()
root.title("Calculator")
root.geometry()
app = App(root)
root.mainloop()
You can bind function to BackSpace in __init__
only when cursor (focus) is in Entry
self.input.bind_all('<BackSpace>', self.cleanInput)
or for all situations
main.bind_all('<BackSpace>', self.cleanInput)
and than you can delete text in Entry and Text
def cleanInput(self, event):
self.input.delete(0, END)
self.log.delete(1.0, END)
BTW: the same way you can bind other keys - for example digits
else:
btn = button(self.btn_frame, c, lambda i=c: self.input.insert(INSERT, i))
main.bind_all(c, lambda event, i=c:self.input.insert(INSERT, i))
EDIT:
full working code:
(issue: at that moment when cursor is in Entry numbers are inserted twice - normaly and by binding)
# python 2.x
#from Tkinter import *
#from tkFont import Font
# python 3.x
from tkinter import *
from tkinter.font import Font
class App:
def __init__(self, tk):
self.tk = tk
self.tk.title("Calculator")
#self.tk.geometry()
self.button_font = Font(family=('Verdana'), size=14)
main_frame = self.create_frame(self.tk)
left_frame = self.create_frame(main_frame)
right_frame = self.create_frame(main_frame)
calc_frame = self.create_frame(left_frame)
self.btnquit = self.create_button(calc_frame, "Quit", self.tk.destroy)
self.btnquit.pack(side = LEFT)
self.log = Text(right_frame, font=Font(family=('Verdana'), size=10), width=25, height=14, background="yellow")
self.log.pack(side=RIGHT)
self.input_text = StringVar()
self.input = Entry(calc_frame, font=self.button_font, width=15, background="white", textvariable=self.input_text)
self.input.pack(side=TOP)
btn_frame = self.create_frame(calc_frame)
for x, key in enumerate( ("()%C", "+-*/", "1234", "5678", "90.=") ):
for y, c in enumerate(key):
if c == "=":
btn = self.create_button(btn_frame, c, self.equalAction)
elif c == "C":
btn = self.create_button(btn_frame, c, self.cleanAction)
else:
btn = self.create_button(btn_frame, c, lambda number=c: self.insertNumber(number))
#main.bind_all(c, lambda event, number=c: self.insertNumber(number))
btn.grid(row=x, column=y)
self.btn_backspace = self.create_button(btn_frame, "<-", self.deleteLastDigit)
self.btn_backspace.grid(row=5, column=2, columnspan=2, sticky="we")
self.btn_loop = self.create_button(btn_frame, "LOOP", self.loopAction)
self.btn_loop.grid(row=5, column=0, columnspan=2, sticky="we")
main_frame.bind_all('<BackSpace>', self.cleanAction)
main_frame.bind_all('<Escape>', self.deleteLastDigit)
def loopAction(self):
bedmas = [ "()", "x^n", "*/", "+-" ]
for element in bedmas:
self.log.insert(INSERT,"\n"+element)
# event=None to use function in command= and in binding
def deleteLastDigit(self, event=None):
self.input_text.set( self.input_text.get()[:-1] )
def insertNumber(self, number):
self.input_text.set( self.input_text.get() + number )
def cleanAction(self):
self.input_text.set("")
self.log.delete(1.0, END)
def equalAction(self):
tmp = self.input_text.get()
try:
result = tmp + "=" + str(eval(tmp))
self.log.insert(1.0, result + "\n");
print(result)
except Exception:
self.log.insert(1.0, "Wrong expression\n");
def create_button(self, frame, text, command=None):
return Button(frame, text=text, font=self.button_font, width=3, command=command)
def create_frame(self, frame, side=LEFT, bg="black"):
f = Frame(frame, background=bg, padx=5, pady=5)
f.pack(side=side, expand=YES, fill=BOTH)
return f
def run(self):
self.tk.mainloop()
#---------------------------------------------------------------------
if __name__ == '__main__':
App(Tk()).run()