Entry returning nothing in print console python - python-3.x

I think it has to do with entry being in a different function not on global so I think I'm having trouble passing Stringvar() variable to a different function and I need to also convert my Stringvar() variable to an int so I can do calculations on it
what my code looks like
https://repl.it/#FiveFourXone/my-code
this is to calculate stuff based on what the entry input is
from tkinter import *
window = Tk()
window.title("my code")
window.geometry("848x480")
window.config(bg="#ececec")
window.resizable(0,0)
def DisplayBTN():
TopFrame = Frame( bg = "#00adee", width = 848, height = 94)
TopFrame.grid(column=0, row=1, pady = 0)
DispCalc = Button( text="Calculate total cost of selected Chook Food", width=30, height=2, bd=2, bg="#124E78", activebackground="#0A2B42", activeforeground="#124E78", fg="#F0F0C9", cursor="hand2", command=DisplayCalc)
DispCalc.grid(column = 0, row = 5,rowspan=1, ipadx = 10, ipady = 10,pady = 0, sticky="w")
def DisplayCalc():
content = Frame( bg = "#00adee", width = 588, height = 300)
content.grid(column=0, columnspan=4, row = 2, rowspan= 4, sticky="E", padx = 15,pady= 1)
LabTitle = Label( font="Arial", fg="#FFF", bg="#00adee", width=30, text="Pick a Food to Calculate")
LabTitle.grid(column=0, columnspan=4, row=1,rowspan=1, padx = 10, pady = 0)
DisplayPell = Button( text="Pellets", width=20, height=1, bd=1, bg="#124E78", activebackground="#0A2B42", activeforeground="#124E78", fg="#F0F0C9", cursor="hand2", command=DisplayCalcA)
DisplayPell.grid(column = 0, row = 3,rowspan=2,columnspan=4, ipadx = 5, ipady = 5,pady = 0,padx = 10, sticky="n")
def callback():
# textvar = DisplayCalcA()
num = textvar.get()
print(num, "entry")
def clear(event, ToCaclc):
ToCaclc.delete(0, END)
def DisplayCalcA():
content = Frame( bg = "#00adee", width = 588, height = 300)
content.grid(column=0, columnspan=4, row = 2, rowspan= 4, sticky="E", padx = 15,pady= 1)
LabTitle = Label( font="Arial", fg="#fff", bg="#00adee",width=30,text="Enter in the weight of Pellets")
LabTitle.grid(column=0, columnspan=4, row=1,rowspan=1, padx = 10, pady = 0)
content = Frame( bg = "#00adee", width = 588, height = 300)
content.grid(column=0, columnspan=4, row = 2, rowspan= 4, sticky="E", padx = 15,pady= 1)
LabTitle = Label( font="Arial", fg="#fff", bg="#00adee",width=30,text="Weight in kg")
LabTitle.grid(column=0, columnspan=2, row=3,rowspan=1, padx = 10, pady = 0)
xDisCalc = Button( text="Submit", width=20, height=2, bd=1, bg="#124E78", activebackground="#0A2B42", activeforeground="#124E78", fg="#F0F0C9", cursor="hand2", command=callback)
xDisCalc.grid(column = 0, row = 3, rowspan=2)
textvar = StringVar()
entry = Entry(window,textvariable=textvar,width = 20,insertbackground="#fff",font=("Arial", 15), bg="#0A2B42", fg="#fff")
entry.grid(row=3, rowspan=1, column = 0, sticky="n")
def DisplayWelc():
content = Frame( bg = "#00adee", width = 588, height = 300)
content.grid(column=0, columnspan=1, row = 2, rowspan= 4, sticky="E", padx = 12,pady= 10)
LabDisHome = Label( font="Arial", fg="#FFF", bg="#00adee", text="Home: Chook n More", width=30, height=2,)
LabDisHome.grid(column=0, columnspan=2, row=1,rowspan= 3,sticky="n", ipadx = 5, ipady = 5,pady = 20,padx = 10,)
LabDisHome = Label( font="Arial", fg="#FFF", bg="#00adee", text="Welcome", width=30, height=2,)
LabDisHome.grid(column=0, columnspan=2, row=2,rowspan= 3,sticky="n", ipadx = 5, ipady = 5,pady = 20,padx = 10,)
DisplayBTN()
DisplayWelc()
window.mainloop()
to be able to print the entry input in different functions so I can use that to calculate stuff

Related

Python 3 tkinter insert file contents into a text box

Okay so I have done about 10 days of searching and I caved in so I'm turning to the community for help.
I am using python 3.6 and tkinter as a user interface.
The basic's of what I'm trying to accomplish is that I have a file that I open and search for a word within the file and insert all the lines that word falls on.
My issue is that its only inserting the first line it finds and I need it to insert all the lines it finds. Sorry for wet coding I'll dry it up once I have functionality later
here's a sample of my code (it's not the full thing but it should give you more than enough info about what I'm trying to accomplish):
import tkinter as tk
from tkinter import ttk
# i added all my imports that this class use's in case you guys think they could pose a problem but they shouldn't be a issue
class EXAMPLEapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.iconbitmap(self, default = "dlm64.ico")
tk.Tk.wm_title(self, "Example.")
self.FILE_MENU_BAR()
self.minsize(width = 360, height = 200)
container = tk.Frame(self)
container.grid(row=0,column=0, sticky="nsew")
container.grid_rowconfigure(0, weight = 1)
container.grid_columnconfigure(0, weight = 1)
self.frames = {}
for FRAME in (SearchPage):
frame = FRAME(container, self)
self.frames[FRAME] = frame
frame.grid(row = 0, column = 0, sticky = "nsew")
self.show_frame(SearchPage)
def FILE_MENU_BAR(self):
#File
self.menubar = tk.Menu()
self.configure(menu = self.menubar)
File_Menu = tk.Menu(self.menubar, tearoff = False)
self.menubar.add_cascade(label = "File", menu = File_Menu)
File_Menu.add_command(label = "EXIT" , command = self.File_EXIT)
# Edit Menu
Edit_Menu = tk.Menu(self.menubar, tearoff = False)
self.menubar.add_cascade(label = "Edit", menu = Edit_Menu)
Edit_Menu.add_command(label = "cut", underline = 2, command = self.Edit_Cut)
Edit_Menu.add_command(label = "copy", underline = 0, command = self.Edit_Copy)
def File_EXIT(self):
sys.exit(0)
def Edit_Cut(self):
print("CUT")
def Edit_Copy(self):
print("COPY")
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class SearchPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text = "Search Inventory", font = ("Helvetica", 20, 'bold', 'underline'))
label.grid(row = 0, column = 1, sticky = "nsew", pady = (0,0), padx = (0,0))
button0 = ttk.Button(self, text = "Inventory Search")
button0.grid(row = 0, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button1 = ttk.Button(self, text = "New Inventory", command = lambda: controller.show_frame(CreatePage))
button1.grid(row = 1, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button2 = ttk.Button(self, text = "Edit Invetory", command = lambda: controller.show_frame(EditPage))
button2.grid(row = 2, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button3 = ttk.Button(self, text = "Ship", command = lambda: controller.show_frame(ShipPage))
button3.grid(row = 3, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button4 = ttk.Button(self, text = "Graph", command = lambda: controller.show_frame(PlotPage))
button4.grid(row = 4, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
DATE_VAR = tk.StringVar()
def DATE_SEARCH():
USER_TEXT = DATE_VAR.get()
with open('SAMPLE.txt', 'r') as searchfile:
for line in searchfile:
if USER_TEXT == '':
LABEL = tk.Text(self, width = 30, height = 2, wrap = tk.WORD, foreground = 'red')
LABEL.grid(row = 6, column = 3, sticky = "nsew", pady = (0,0), padx = (20,0))
LABEL.insert(1.0, "PLEASE ENTER A VALUE")
LABEL.configure(state = 'disabled')
break
elif USER_TEXT in line:
LABEL = tk.Text(self, width = 100, height = 4, wrap = tk.WORD)
LABEL.grid(row = 6, column = 3, sticky = "e", pady = (0,0), padx = (20,0))
LABEL.insert(1.0, line)
LABEL.configure(state = 'disabled')
ScrollBar = tk.Scrollbar(self)
ScrollBar.config(command = LABEL.yview)
LABEL.config(yscrollcommand = ScrollBar.set)
ScrollBar.grid(row = 6, column = 4, sticky = "e")
break
else:
LABEL = tk.Text(self, width = 30, height = 2, wrap = tk.WORD, foreground = 'red')
LABEL.grid(row = 6, column = 3, sticky = "nsew", pady = (0,0), padx = (20,0))
LABEL.insert(1.0, "INVENTORY DOES NOT EXIST")
LABEL.configure(state = 'disabled')
DATE_Search_label = tk.Label(self, text = "Search by DATE", font = ("Helvetica", 9))
DATE_Search_label.grid(row = 5, column = 1, sticky = "nsew")
DATE_Search_Entry = tk.Entry(self, textvariable = DATE_VAR)
DATE_Search_Entry.grid(row = 6, column = 1, sticky = "nsew", pady = 0, padx = 2)
DATE_SEARCH_BUTTON = ttk.Button(self, text = "Search", command = DATE_SEARCH)
DATE_SEARCH_BUTTON.grid(row = 6, column = 2, sticky = "nsew")
app = EXAMPLEapp()
app.mainloop()
EDIT:
I have made several changes to your code.
There were way too many emblems with the way you had it set up.
As I am not 100% sure how what you are trying to accomplish I have made progress with your code.
Below is the edited version of your code.
I also created a text file on my end to test with and it seams to have worked so let me know if this is getting close to what you are attempting to do.
A few notes:
1st I moved everything into one class. The way you had it set up was just not going to work without some major changes.
2nd I needed to add self. to many of your variables because they are variables that we need to interact with in the class.
3rd I changed they way you get the data from the entry box. The way you were doing it was just not working so I simplified it by adding .get() function to the entry variable.
4th but probably should have been the 1st thing I mentions. The way you had your main Tk() window starting was odd. I changed how root was created and how we pass it into the class. This seams to make more sense to me.
This is much better to use IMO.
Let me know what parts you still need explanation on and I will make updates to my answer as needed.
Update:
change the while open statement a bit. You do not need to recreate the text box and reconfigure it ever for loop this is not good and will prevent you from seeing multiple items. Also I do not believe you can have a multi line label thought I have never tried. Lets change this to a text box this should do what we need.
import tkinter as tk
from tkinter import ttk
class EXAMPLEapp(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.root = parent
self.root.wm_title("TM Duch\'e Nut CO.")
self.FILE_MENU_BAR()
self.root.minsize(width = 360, height = 200)
self.container = tk.Frame(self.root)
self.container.grid(row=0,column=0, sticky="nsew")
self.container.grid_rowconfigure(0, weight = 1)
self.container.grid_rowconfigure(6, weight = 0)
self.container.grid_columnconfigure(0, weight = 1)
self.container.grid_columnconfigure(3, weight = 0)
self.label = tk.Label(self.root, text = "Search Inventory", font = ("Helvetica", 20, 'bold', 'underline'))
self.label.grid(row = 0, column = 1, sticky = "nsew", pady = (0,0), padx = (0,0))
self.button0 = ttk.Button(self.root, text = "Inventory Search")
self.button0.grid(row = 0, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button1 = ttk.Button(self.root, text = "New Inventory", command = lambda: controller.show_frame(CreatePage))
self.button1.grid(row = 1, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button2 = ttk.Button(self.root, text = "Edit Invetory", command = lambda: controller.show_frame(EditPage))
self.button2.grid(row = 2, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button3 = ttk.Button(self.root, text = "Ship", command = lambda: controller.show_frame(ShipPage))
self.button3.grid(row = 3, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button4 = ttk.Button(self.root, text = "Graph", command = lambda: controller.show_frame(PlotPage))
self.button4.grid(row = 4, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.DATE_Search_label = tk.Label(self.root, text = "Search by DATE", font = ("Helvetica", 9))
self.DATE_Search_label.grid(row = 5, column = 1, sticky = "nsew")
self.DATE_Search_Entry = tk.Entry(self.root)
self.DATE_Search_Entry.grid(row = 6, column = 1, sticky = "nsew", pady = 0, padx = 2)
self.DATE_SEARCH_BUTTON = ttk.Button(self.root, text = "Search", command = lambda: self.DATE_SEARCH())
self.DATE_SEARCH_BUTTON.grid(row = 6, column = 2, sticky = "nsew")
def DATE_SEARCH(self):
with open('SAMPLE.txt', 'r') as f:
search_f = f.readlines()
self.text = tk.Text(self.root, width = 30, height = 2)
self.text.grid(row = 6, column = 3, sticky = "ew", pady = (0,0), padx = (20,0))
self.ScrollBar = tk.Scrollbar(self.root)
self.ScrollBar.config(command = self.text.yview)
self.text.config(yscrollcommand = self.ScrollBar.set)
self.ScrollBar.grid(row = 6, column = 4, sticky = "ns")
self.text.delete(1.0, "end-1c")
USER_TEXT = self.DATE_Search_Entry.get()
if USER_TEXT == '':
self.text.config(foreground = 'red')
self.text.insert(tk.END, "PLEASE ENTER A VALUE")
else:
match_in_file = False
for line in search_f:
if USER_TEXT in line:
self.text.config(foreground = 'black')
self.text.insert(tk.END, "{}".format(line))
match_in_file = True
if match_in_file == False:
self.text.config(foreground = 'red')
self.text.insert(tk.END, "INVENTORY DOES NOT EXIST")
def FILE_MENU_BAR(self):
#File
self.menu = tk.Menu(self.root)
self.root.config(menu = self.menu)
self.fileMenu = tk.Menu(self.menu, tearoff = 0)
self.menu.add_cascade(label = "File", menu = self.fileMenu)
self.fileMenu.add_separator()
self.fileMenu.add_command(label = "Exit", command = lambda: self.root.destroy())
# Edit Menu
self.Edit_Menu = tk.Menu(self.menu)
self.menu.add_cascade(label = "Edit", menu = self.Edit_Menu)
self.Edit_Menu.add_command(label = "cut", underline = 2, command = self.Edit_Cut)
self.Edit_Menu.add_command(label = "copy", underline = 0, command = self.Edit_Copy)
def File_EXIT(self):
sys.exit(0)
def Edit_Cut(self):
print("CUT")
def Edit_Copy(self):
print("COPY")
root = tk.Tk()
app = EXAMPLEapp(root)
app.mainloop()

getting a variable from one class to another class

i would like to get a variable from one of my classes to the another class.
the variable that i want to use is profile which is on line 129. i would like to use this variable outside of this class and into the class AddJob() down at the bottom of my code. it would much appreciated if anyone could possibly just give me a solution as i have been trying to get this to work for days.
import tkinter
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
from tkinter.scrolledtext import ScrolledText
import sqlite3
from sqlite3 import Error
import webbrowser
import re
Background = ("WHITE")
LARGE_FONT = ("Verdana", 9)
HOME_FONT = ("Times", 15, "bold")
EMAIL_FONT = ("times", 9)
def DataBase():
with sqlite3.connect("UserInfo.db") as db:
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users(
userID INTEGER PRIMARY KEY,
username STRING,
password STRING,
firstname STRING,
surname STRING,
email STRING);
''')
cursor.execute ('''
CREATE TABLE IF NOT EXISTS jobs(
jobID INTEGER PRIMARY KEY,
userID
jobtitle STRING,
jobdescript STRING);
''')
class MsgBox(tkinter.Toplevel):
def __init__(self, title = "", message = ""):
tkinter.Toplevel.__init__(self)
self.title(title)
self.label = tkinter.Label(self, text = message)
self.label['bg'] = 'white'
self.label.pack(ipadx = 10, ipady = 10, fill = 'both', expand = True)
self.button = tkinter.Button(self, text = "OK")
self.button['command'] = self.destroy
self.button.pack(pady = 10, padx = 10, ipadx = 20, side = 'right')
class JobApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side = "top", fill = "both", expand = True)
container.grid_rowconfigure(0, weight = 1)
container.grid_columnconfigure(0, weight = 1)
self.frames = {}
#this is where you add a page to the program so you can add different functions
for F in (LoginPage, SignUp, HomePage, MenuPage, MapPage, ProfilePage, SettingsPage, JobsPage, AddJob):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row = 0, column = 0, sticky = "nsew")
self.show_frame(LoginPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
DataBase()
class LoginPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.Logo = PhotoImage(file = "Logo.gif")
def Log_in():
with sqlite3.connect("UserInfo.db") as db:
cursor = db.cursor()
user = (self.UserEntry.get())
Pass = (self.PassEntry.get())
if user == "" or Pass == "":
msg = MsgBox("", "Make sure to fill all the boxes\nPlease try again")
msg.label['font'] = 'Verdana 10'
msg.button['text'] = 'Close'
msg.button.pack(expand = True)
else:
dictionary = {}
cursor.execute("SELECT username, password FROM users")
for pword in cursor.fetchall():
(key ,val) = tuple(pword)
dictionary[str(key)] = val
if user in dictionary:
if dictionary[user] == Pass:
sql = '''SELECT userID FROM users WHERE username = ?'''
cursor.execute(sql, (user,))
profile = cursor.fetchall()
controller.show_frame(HomePage)
self.UserEntry.delete(0, 'end')
self.PassEntry.delete(0, 'end')
else:
messagebox.showinfo("", "Enter the correct password")
self.PassEntry.delete(0, 'end')
self.logo = tk.Label(self, image = self.Logo)
self.User = tk.Label(self, text = "User Name:").place(x = 72, y = 130)
self.Pass = tk.Label(self, text = "Password:").place(x = 80, y = 155)
self.UserEntry = Entry(self)
self.PassEntry = Entry(self, show = '*')
self.login = ttk.Button(self, text = "Login", command = Log_in)
self.signup = ttk.Button(self, text = "Create account",
command = lambda:controller.show_frame(SignUp))
self.UserEntry.place(width = 100, height = 20, x = 140, y = 130)
self.PassEntry.place(width = 100, height = 20, x = 140, y = 155)
self.login.place(x = 80, y = 180)
self.signup.place(x = 160, y = 180)
self.logo.place(x = 110, y = 20)
class SignUp(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
def Save_info():
DataBase()
with sqlite3.connect("UserInfo.db") as db:
cursor = db.cursor()
FnameEntry = self.FnameEntry.get()
SnameEntry = self.SnameEntry.get()
EmailEntry = self.EmailEntry.get()
UserNameEntry = self.UserNameEntry.get()
PassWordEntry = self.PassWordEntry.get()
RenterPasswordEntry = self.RenterPasswordEntry.get()
check = []
cursor.execute("SELECT * FROM users")
for row in cursor.fetchall():
check.append(row)
print (check)
if not re.match(r"[^#]+#[^#]+\.[^#]+", EmailEntry):
messagebox.showinfo("ERROR", "the email that you entered was not valid\nPlease try again")
if len(FnameEntry) == 0 or len(SnameEntry) == 0 or len(EmailEntry) == 0 or len(UserNameEntry) == 0 or len(PassWordEntry) == 0 or len(RenterPasswordEntry) == 0:
messagebox.showinfo("No fill", "You didn't fill all the fields")
else:
if len(UserNameEntry) < 6:
messagebox.showinfo("Not long enough", "your username wasn't long enough\nPlease try again")
else:
if len(PassWordEntry) < 6:
messagebox.showinfo("Not long enough", "Your password wasn't long enough\nPlease try again")
else:
if RenterPasswordEntry != PassWordEntry:
messagebox.showinfo("pass word match up", "Your passwords didn't seem to match up\nPlease try again")
else:
if UserNameEntry in check:
messagebox.showinfo("", "The user name that you entered already exsists\nPlease enter a different one")
self.UserNameEntry.delete(0, 'end')
self.PassWordEntry.delete(0, 'end')
self.RenterPasswordEntry.delete(0, 'end')
else:
YesNo = messagebox.askokcancel("Continue", "would you like to go back to the login page")
if YesNo == True:
self.FnameEntry.delete(0, 'end')
self.SnameEntry.delete(0, 'end')
self.EmailEntry.delete(0, 'end')
self.UserNameEntry.delete(0, 'end')
self.PassWordEntry.delete(0, 'end')
self.RenterPasswordEntry.delete(0, 'end')
cursor.execute("""
INSERT INTO users (username,password,firstname,surname,email)
VALUES (?, ?, ?, ?, ?)
""", (UserNameEntry, PassWordEntry, FnameEntry, SnameEntry, EmailEntry))
db.commit()
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())
controller.show_frame(LoginPage)
self.x = ttk.Label(self, text = "fill in the information to create an account.\n\nBoxes with * next to them must be filled in.\nYour Username must be longer than 6 characters.\nYour password must be longer than 6 characters.\n", font = LARGE_FONT).grid(row = 0, column = 0, columnspan = 2)
self.Fname = ttk.Label(self, text = "First Name *:", font = LARGE_FONT).grid(row = 1, sticky = "e")
self.Sname = ttk.Label(self, text = "Surname *:", font = LARGE_FONT).grid(row = 2, sticky = "e")
self.Email = ttk.Label(self, text = "Email Address *:", font = LARGE_FONT).grid(row = 3, sticky = "e")
self.UserName = ttk.Label(self, text = "User name *:", font = LARGE_FONT).grid(row = 4, sticky = "e")
self.PassWord = ttk.Label(self, text = "Password *:", font = LARGE_FONT).grid(row = 5, sticky = "e")
self.ReneterPassword = ttk.Label(self, text = "Confirm password *:", font = LARGE_FONT).grid(row = 6, sticky = "e")
self.blank = ttk.Label(self, text = "").grid(row = 8)
Continue = ttk.Button(self, text = "Continue",
command = Save_info).grid(row = 9, rowspan = 2, stick = "e")
Cancel = ttk.Button(self , text = "Cancel",
command= lambda:controller.show_frame(LoginPage)).grid(row = 9, column = 1, stick = "w")
self.FnameEntry = Entry(self)
self.SnameEntry = Entry(self)
self.EmailEntry = Entry(self)
self.UserNameEntry = Entry(self)
self.PassWordEntry = Entry(self)
self.RenterPasswordEntry = Entry(self)
self.FnameEntry.grid(row = 1, column = 1, sticky = "w")
self.SnameEntry.grid(row = 2, column = 1, sticky = "w")
self.EmailEntry.grid(row = 3, column = 1, sticky = "w")
self.UserNameEntry.grid(row = 4, column = 1, sticky = "w")
self.PassWordEntry.grid(row = 5, column = 1, sticky = "w")
self.RenterPasswordEntry.grid(row = 6, column = 1, sticky = "w")
class HomePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
def on_entry_click(event):
if self.postcode.get() == 'Postcode':
self.postcode.delete(0, "end")
self.postcode.insert(0, '')
self.postcode.config(fg = 'black')
def on_focusout(event):
if self.postcode.get() == '':
self.postcode.delete(0, "end")
self.postcode.insert(0, 'Postcode')
self.postcode.config(fg = 'grey')
def on_entry_click2(event):
if self.searchjob.get() == 'Enter a job you want to search for..':
self.searchjob.delete(0, "end")
self.searchjob.insert(0, '')
self.searchjob.config(fg = 'black')
def on_focusout2(event):
if self.searchjob.get() == '':
self.searchjob.delete(0, "end")
self.searchjob.insert(0, 'Enter a job you want to search for..')
self.searchjob.config(fg = 'grey')
Homepagecanvas = Canvas(self, width = 320, height = 568)
Homepagecanvas.pack()
TopBarHome = Homepagecanvas.create_rectangle(0, 0, 320, 50, fill = 'light grey')
Home = Homepagecanvas.create_text((80, 25), text = "Home", font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Menu",
command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)
self.postcode = Entry(self)
self.searchjob = Entry(self)
self.postcode.insert(0, 'Postcode')
self.postcode.bind('<FocusIn>', on_entry_click)
self.postcode.bind('<FocusOut>', on_focusout)
self.postcode.config(fg = 'grey')
self.postcode.place(width = 60, height = 30, x = 10, y = 60)
self.searchjob.insert(0, 'Enter a job you want to search for..')
self.searchjob.bind('<FocusIn>', on_entry_click2)
self.searchjob.bind('<FocusOut>', on_focusout2)
self.searchjob.config(fg = 'grey')
self.searchjob.place(width = 220, height = 30, x = 80, y = 60)
scrollbar = Scrollbar(self)
scrollbar.place(width = 10, height =
450, x = 10, y = 100)
Joblist = Listbox(self, yscrollcommand = scrollbar.set)
for line in range(100):
Joblist.insert(END, "This is line number " + str(line))
Joblist.place(height = 450, width = 280, x = 25, y = 100)
scrollbar.config(command = Joblist.yview)
class MenuPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
Homepagecanvas = Canvas(self, width = 320, height = 568)
Homepagecanvas.pack()
TopBarHome = Homepagecanvas.create_rectangle(0, 0, 320, 50, fill = 'light grey')
Home = Homepagecanvas.create_text((40, 15), text = "Menu", font = HOME_FONT)
Home = Homepagecanvas.create_text((160, 35), text = "here you can navigate to other pages in the application")
Home = tk.Button(self,
text = "Home Page",
relief = GROOVE,
command = lambda:controller.show_frame(HomePage)).place(width = 100, height = 30, x = 10, y = 60)
Map = tk.Button(self,
text = "Map",
relief = GROOVE,
command = lambda:controller.show_frame(MapPage)).place(width = 100, height = 30, x = 10, y = 90)
Profile = tk.Button(self,
text = "Profile",
relief = GROOVE,
command = lambda:controller.show_frame(ProfilePage)).place(width = 100, height = 30, x = 10, y = 120)
Settings = tk.Button(self,
text = "Settings",
relief = GROOVE,
command = lambda:controller.show_frame(SettingsPage)).place(width = 100, height = 30, x = 10, y = 150)
Jobs = tk.Button(self,
text = "Jobs",
relief = GROOVE,
command = lambda:controller.show_frame(JobsPage)).place(width = 100, height = 30, x = 10, y = 180)
class MapPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
MapPageCanvas = Canvas(self, width = 320, height = 568)
MapPageCanvas.pack()
TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
fill = 'light grey')
Home = MapPageCanvas.create_text((80, 25),
text = "Map",
font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Menu",
command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)
class ProfilePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
def on_entry_click(event):
if self.postcode.get() == 'Postcode':
self.postcode.delete(0, "end")
self.postcode.insert(0, '')
self.postcode.config(fg = 'black')
def on_focusout(event):
if self.postcode.get() == '':
self.postcode.delete(0, "end")
self.postcode.insert(0, 'Postcode')
self.postcode.config(fg = 'grey')
ProfilePageCanvas = Canvas(self, width = 320, height = 568)
ProfilePageCanvas.pack()
TopBar = ProfilePageCanvas.create_rectangle(0, 0, 320, 50,
fill = 'light grey')
Profile = ProfilePageCanvas.create_text((80, 25), text = "Profile",
font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Menu",
command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)
def logout():
result = messagebox.askokcancel("Logout", "would you like to logout")
if result == True:
controller.show_frame(LoginPage)
Logout = ttk.Button(self, text = "Logout",
command = logout).place(width = 60, height = 40, x = 255 , y = 5)
class SettingsPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
MapPageCanvas = Canvas(self, width = 320, height = 568)
MapPageCanvas.pack()
TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
fill = 'light grey')
Home = MapPageCanvas.create_text((90, 25),
text = "Settings",
font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Menu",
command = lambda:controller.show_frame(MenuPage)
).place(height = 40, width = 40, x = 5, y = 5)
def BG():
app.configure(background = Background)
def Toggle():
if DarkTheme.config('relief')[-1] == 'flat':
DarkTheme.config(relief = "sunken", bg = 'grey')
else:
DarkTheme.config(relief = "flat", bg = 'white')
Background = "DARK GRAY"
BG()
DarkTheme = tk.Button(self,
bg = 'white',
highlightbackground = 'black',
text = "Dark Theme",
pady = 5, padx = 5,
relief = "flat",
command = Toggle)
DarkTheme.place(x = 5, y = 60)
class JobsPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
MapPageCanvas = Canvas(self, width = 320, height = 568)
MapPageCanvas.pack()
TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
fill = 'light grey')
Home = MapPageCanvas.create_text((80, 25),
text = "Jobs",
font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Menu",
command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)
addjob = ttk.Button(self, text = "Add Job",
command = lambda:controller.show_frame(AddJob)).place(height = 40, width = 60, x = 255, y = 5)
class AddJob(tk.Frame, LoginPage):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
def dbAddJob():
JobT = self.Jt.get("1.0", 'end').rstrip('\n')
JobD = self.Jd.get("1.0", 'end').rstrip('\n')
with sqlite3.connect("UserInfo.db") as db:
cursor = db.cursor()
if JobT == "" or JobD == "":
messagebox.showinfo("Invalid","please fill in the boxes or cancel")
else:
aj = messagebox.askokcancel("Continue", "Job added click ok to continue\nor cancel or change what you have added")
if aj == True:
cursor.execute("""
INSERT INTO jobs (jobtitle, jobdescript)
VALUES (?, ?)
""", (JobT, JobD))
db.commit()
self.Jt.delete('1.0', END)
self.Jd.delete('1.0', END)
controller.show_frame(JobsPage)
cursor.execute("SELECT * FROM jobs")
print(cursor.fetchall())
MapPageCanvas = Canvas(self, width = 320, height = 568)
MapPageCanvas.pack()
TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
fill = 'light grey')
Home = MapPageCanvas.create_text((100, 25),
text = "Add a Job",
font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Back",
command = lambda:controller.show_frame(JobsPage)).place(height = 40, width = 40, x = 5, y = 5)
self.Addjobbutton = ttk.Button(self, text = "Add",
command = dbAddJob).place(width = 60, height = 30, x = 90, y = 520)
self.Cancel = ttk.Button(self, text = "cancel",
command = lambda:controller.show_frame(JobsPage)).place(width = 60, height = 30, x = 170, y = 520)
self.Jt = ScrolledText(self)
self.Jd = ScrolledText(self)
self.Jt.place(height = 30, width = 310, x = 5, y = 60)
self.Jd.place(height = 400, width = 310, x = 5, y = 100)
app = JobApp()
app.geometry('320x568')
app.resizable(0,0)
app.mainloop()
Are you trying to make it a global variable such as ?
sound = None
class Cat(object):
global sound
"""
All your code
"""
sound = "meow"
Now if you use 'global sound' you can acces the global variable from everywhere, now sound returns:
>>> sound
'meow'
This way you can acces a variable from without a class or function.

python function complains about global variable not being defined

when I moved the code into functions the calculation will not work now. Complains:
NameError: global name 'feet' is not defined
How do I fix this so the method sees the variable correctly?
from tkinter import * # Import tkinter
from tkinter import ttk
def calculate(*args):
try:
value = float(feet.get())
meters.set((0.3048 * value * 10000.0 + 0.5)/ 10000.0)
except ValueError:
pass
def frame():
mainframe = ttk.Frame(root, padding = "3 3 12 12")
mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
feet = StringVar()
meters = StringVar()
feet_entry = ttk.Entry(mainframe, width = 7, justify = CENTER, textvariable = feet)
feet_entry.grid(column = 2, row = 1, sticky = (W, E))
ttk.Label(mainframe, textvariable = meters).grid(column = 2, row = 2, sticky = (W, E))
ttk.Button(mainframe, text = "Calculate", command = calculate).grid(column = 3, row = 3, sticky = (W))
ttk.Label(mainframe, text = "feet").grid(column = 3, row = 1, sticky = (W))
ttk.Label(mainframe, text = "is equivalent to:").grid(column = 1, row = 2, sticky = (E))
ttk.Label(mainframe, text = "meters").grid(column = 3, row = 2, sticky = (W))
for child in mainframe.winfo_children(): child.grid_configure(padx = 5, pady = 5)
feet_entry.focus()
root.bind('<Return>', calculate)
# create a Tkinter window
root = Tk()
root.title("Menu Bar")
frame()
# start the event loop
root.mainloop()
Make feet and meters instance attributes by replacing them everywhere by self.feet and self.meters, to get
value = float(self.feet.get())
self.meters.set((0.3048 * value * 10000.0 + 0.5)/ 10000.0)
...
self.feet = StringVar()
self.meters = StringVar()
feet_entry = ttk.Entry(mainframe, width = 7, justify = CENTER,
textvariable = self.feet)
feet_entry.grid(column = 2, row = 1, sticky = (W, E))
ttk.Label(mainframe, textvariable = self.meters
).grid(column = 2, row = 2, sticky = (W, E))

Overflow anticipation/Timeout Mac OS X

I have a calculator program that can do exponent calculations, but it doesn't like (cannot process) things like 10^10000000000000. I saw a previous post that said use signal to timeout but that was only unix. Another bit about my code: when equals is pressed, it runs the input through a try block, with the exception printing ERROR to the display of the calculator. Is there any way I can detect a potential overflow and raise an error or timeout after some time has elapsed (raising an error)? Note: File needs to be transferred to another system, so the solution must be versatile. Thanks!
EDIT: I am using python to run tkinter to make the GUI below. I need to transfer the file to my raspberry pi running Jessie.
from tkinter import *
import math
class Calc:
def __init__(self,master):
self.master = master
self.lastbutton = ''
self.varlist = dict()
self.varlist = {"A":"0","B":"0","C":"0","D":"0","E":"0","F":"0","G":"0","H":"0","I":"0","J":"0"}
self.dlist = dict()
self.dlist = {'^':'**','sqrt(':'math.sqrt(',')cubrt':'**(1/3)',
'sin(':'math.sin(','cos(':'math.cos(','tan(':'math.tan(',
'arcsin(':'math.asin(','arccos(':'math.acos(','arctan(':'math.atan(',"τ":"(math.tau)",
'π':'(math.pi)','e':'(math.e)',"e^":"math.exp(",'(π/2)':'((math.pi)/2)','(π/3)':'((math.pi)/3)','(π/4)':'((math.pi)/4)',
"A":"self.varlist['A']","B":"self.varlist['B']","C":"self.varlist['C']","D":"self.varlist['D']",
"E":"self.varlist['E']","F":"self.varlist['F']","G":"self.varlist['G']","H":"self.varlist['H']",
"I":"self.varlist['I']","J":"self.varlist['J']",
"mod(":"math.fmod(","e^(":"math.exp(","ln(":"math.log(","log(":"math.log10(","log b (":"math.log(",
"sec(":"(1/math.cos(","csc(":"(1/math.sin(","cot(":"(1/math.tan(","arcsec(":"(1/math.acos(","arccsc(":"(1/math.asin(","arccot(":"(1/math.atan(",
"toRadians(":"math.radians(","toDegrees":"math.degrees(","hypot(":"math.hypot("}
self.text1 = StringVar(value = '1')
self.text2 = StringVar(value = '2')
self.text3 = StringVar(value = '3')
self.text4 = StringVar(value = '4')
self.text5 = StringVar(value = '5')
self.text6 = StringVar(value = '6')
self.text7 = StringVar(value = '7')
self.text8 = StringVar(value = '8')
self.text9 = StringVar(value = '9')
self.text0 = StringVar(value = '0')
self.acl = StringVar(value = 'Del')
self.period = StringVar(value = '.')
self.shft = StringVar(value = 'shft1')
self.var1 = StringVar()
self.var2 = StringVar()
self.var3 = StringVar()
self.option1 = ['^2','^3','sqrt(',')cubrt','^','mod(','ln(','log(','log b (']
self.option2 = ['τ','π','e','e^','(π/2)','(π/3)','(π/4)','toRadians(','toDegrees(']
self.option3 = ['sin(','cos(','tan(','arcsin(','arccos(','arctan(', 'sec(', 'csc(','cot(','arcsec(','arccsc(','arccot(','hypot(']
self.master.title('My Calculator')
self.displaya = Entry(master)
self.displaya.grid(row = 0, columnspan = 6)
self.displayb = Entry(master)
self.displayb.grid(row = 1, columnspan = 6)
self.displayc = Entry(master)
self.displayc.grid(row = 2, columnspan = 6)
self.one = Button(master, textvariable = self.text1,width = 10, command = lambda: self.display(self.text1.get()))
self.one.grid(row = 4, column = 0)
self.two = Button(master, textvariable = self.text2,width = 10, command = lambda: self.display(self.text2.get()))
self.two.grid(row = 4, column = 1)
self.three = Button(master, textvariable = self.text3, width = 10,command = lambda: self.display(self.text3.get()))
self.three.grid(row = 4, column = 2)
self.four = Button(master, textvariable = self.text4, width = 10,command = lambda: self.display(self.text4.get()))
self.four.grid(row = 5, column = 0)
self.five = Button(master, textvariable = self.text5,width = 10, command = lambda: self.display(self.text5.get()))
self.five.grid(row = 5, column = 1)
self.six = Button(master, textvariable = self.text6,width = 10, command = lambda: self.display(self.text6.get()))
self.six.grid(row = 5, column = 2)
self.seven = Button(master, textvariable = self.text7,width = 10, command = lambda: self.display(self.text7.get()))
self.seven.grid(row = 6, column = 0)
self.eight = Button(master, textvariable = self.text8, width = 10,command = lambda: self.display(self.text8.get()))
self.eight.grid(row = 6, column = 1)
self.nine = Button(master, textvariable = self.text9, width = 10,command = lambda: self.display(self.text9.get()))
self.nine.grid(row = 6, column = 2)
self.zero = Button(master, textvariable = self.text0, width = 10,command = lambda: self.display(self.text0.get()))
self.zero.grid(row = 7, column = 1)
self.result = Button(master, text = '=', width = 10, height = 1, command = lambda : self.equals())
self.result.grid(row = 7, column = 0)
self.ac = Button(master, textvariable = self.acl, width = 10, height = 1, command = lambda : self.clear(self.acl.get()))
self.ac.grid(row = 7, column = 2)
self.plus = Button(master, text = '+', width = 10, height = 1, command = lambda : self.display('+'))
self.plus.grid(row = 4, column = 3)
self.minus = Button(master, text = '-', width = 10, height = 1, command = lambda : self.display('-'))
self.minus.grid(row = 5, column = 3)
self.times = Button(master, text = '*', width = 10, height = 1, command = lambda : self.display('*'))
self.times.grid(row = 6, column = 3)
self.div = Button(master, text = '/', width = 10, height = 1, command = lambda : self.display('/'))
self.div.grid(row = 7, column = 3)
self.per = Button(master, textvariable = self.period, width = 4, command = lambda : self.display(self.period.get()))
self.per.grid(row = 1, column = 0)
self.opp = Button(master, text = '(', width = 1, height = 1, command = lambda : self.display('('))
self.opp.grid(row = 0, column = 1)
self.clp = Button(master, text = ')', width = 1, height = 1, command = lambda : self.display(')'))
self.clp.grid(row = 1, column = 1)
self.update_button = Button(master, textvariable = self.shft, width = 4, command = lambda: self.update(int(self.shft.get()[4:5])))
self.update_button.grid(row = 0, column = 0)
self.store = Button(master, text = 'sto', command = lambda : self.sto(self.displayc.get()))
self.store.grid(row = 2, column = 1)
self.menu1 = OptionMenu(master, self.var1, *self.option1)
self.menu1.grid(row = 4, column = 4, ipadx = 20)
self.menu2 = OptionMenu(master, self.var2, *self.option2)
self.menu2.grid(row = 5, column = 4, ipadx = 20)
self.menu3 = OptionMenu(master, self.var3, *self.option3)
self.menu3.grid(row = 6, column = 4, ipadx = 20)
self.place1 = Button(root, text = 'Place', width = 10, height = 1, command = lambda : self.display(self.var1.get()))
self.place1.grid(row = 4, column = 5)
self.place2 = Button(root, text = 'Place', width = 10, height = 1, command = lambda : self.display(self.var2.get()))
self.place2.grid(row = 5, column = 5)
self.place3 = Button(root, text = 'Place', width = 10, height = 1, command = lambda : self.display(self.var3.get()))
self.place3.grid(row = 6, column = 5)
self.hbox = Text(master, height = 5, width = 35)
self.hbox.grid(row = 1, rowspan = 3, column = 4, columnspan = 2)
self.help = Button(master, text = 'Help', command = lambda : self.hlp())
self.help.grid(row = 2, column = 0)
def update(self, mode):
if mode == 1:
self.text1.set('A')
self.text2.set('B')
self.text3.set('C')
self.text4.set('D')
self.text5.set('E')
self.text6.set('F')
self.text7.set('G')
self.text8.set('H')
self.text9.set('I')
self.text0.set('J')
self.acl.set('AC')
self.period.set(',')
self.shft.set('shft2')
else:
self.text1.set('1')
self.text2.set('2')
self.text3.set('3')
self.text4.set('4')
self.text5.set('5')
self.text6.set('6')
self.text7.set('7')
self.text8.set('8')
self.text9.set('9')
self.text0.set('0')
self.acl.set('Del')
self.period.set('.')
self.shft.set('shft1')
def sto(self, dis):
disl = dis.split(',')
var = disl[0]
val = disl[1]
self.varlist[var] = val
self.displaya.delete(0,END)
self.displaya.insert(0, self.displayb.get())
self.displayb.delete(0,END)
txt = val + '-->' + var
self.displayb.insert(0, txt)
self.displayc.delete(0,END)
self.displayc.insert(0, round(float(val), 7))
self.lastbutton = 'sto('
def hlp(self):
self.hbox.delete(1.0, END)
sme = dict()
sme = {"-":"+","*":"+","/":"+","B":"A","C":"A","D":"A","E":"A","F":"A","G":"A","H":"A","I":"A","J":"A",
"cos(":"sin(","tan(":"sin(","arcsin(":"sin(","arccos(":"sin(","arctan(":"sin(",
"sec(":"sin(","csc(":"sin(","cot(":"sin(","arcsec(":"sin(","arccsc(":"sin(","arccot(":"sin("}
bh = dict()
bh = {"+":"+, -, *, / \n Arithmetic operators (op)\n format : x op y",
"sin(":"sin(), cos(), etc\n Trigonometric functions (funct()) \nformat : funct(x)",
"A":"Variables can hold 1 value\nat a time with STO\nuse like number",
"^2":"Square (exponent = 2)\n format : x^2",
"^":"Carrot (x ^ y)\n format : x^y",
")cubrt":"Cube root\n format : (x)cubrt",
"sqrt(":"Square root\n format : sqrt(x)",
"mod(":"Modulo (remainder x/y)\nformat : mod(x,y)",
"ln(":"Natural log\n format : ln(x)",
"log(":"Log base 10\n format : log(x)",
"log b (":"Logarithm of base b\n format : log(x,b)",
"sto(":"Store value to variable\n format : sto(variable,value)",
"hypot(":"Hypotenuse (Pythagorean theorem)\n Find hypotenuse given two sides\n format : hypot(s1,s2)"}
helpfunct = sme[self.lastbutton] if self.lastbutton in sme.keys() else self.lastbutton
new = bh[helpfunct] if helpfunct in bh.keys() else "No help available for this item"
add = 'Help:' + '\n' + new
self.hbox.insert(1.0, add)
def display(self,e):
self.displayc.insert(END,e)
self.lastbutton = e
def equals(self):
self.displaya.delete(0,END)
b = self.displayb.get()
self.displaya.insert(0, b)
self.displayb.delete(0,END)
c = self.displayc.get()
for key in self.dlist:
c = c.replace(key, self.dlist[key])
try:
equals = round(float(eval(c)),7)
c = c + '=' + str(equals)
self.displayb.insert(0, c)
self.displayc.delete(0,END)
self.displayc.insert(0, equals)
except ZeroDivisionError:
self.displayb.insert(0,c)
c = 'Error: Div by Zero: '
self.displayc.insert(0,c)
except SyntaxError:
self.displayb.insert(0,c)
c = 'Error: Syntax'
self.displayc.delete(0,END)
self.displayc.insert(0,c)
except IndexError:
self.displayb.insert(0,c)
c = 'Error: Syntax'
self.displayc.delete(0,END)
self.displayc.insert(0,c)
except TypeError:
self.displayb.insert(0,c)
c = 'Error: Syntax'
self.displayc.delete(0,END)
self.displayc.insert(0,c)
return
def clear(self, com):
if com == 'AC':
if len(self.displayc.get()) == 0:
self.displayb.delete(0, END)
self.displaya.delete(0, END)
else:
self.displayc.delete(0, END)
else:
self.displayc.delete(len(self.displayc.get())-1,END)
return
root = Tk()
calc = Calc(root)
root.mainloop()
Your particular problem is the expression 10^10000000000000 (which you translate to 10**10000000000000 contains only integers and Python supports arbitrary precision integers so it is attempting to give you an answer...
However from your code it is clear you are writing a floating-point calculator. If you change the expression to 10.0**10000000000000.0 you will get an instant overflow exception, add in a try:except: and you can catch that and display a suitable result.
You will need to figure out how add the .0's in your code. You should also consider what happens if your user enters, for example, 3+*4 or other rubbish. Ask yourself whether using eval is really the best way to implement a calculator.
HTH

Odd grid sizing behaviour

I have been using tkinter's grid geometry manager and have configured all the rows and columns to weight = 1. The problem comes when I try to resize a Tk() window. When I resize it vertically only, the width of widgets and the proportion of column widths also change despite their equal weight. Furthermore, the width of the columns isn't in the desired proportions (i.e. all equal) before doing any resizing - to be precise the first column (with labels and buttons) is as wide as other two (holding a canvas with columnspan = 2 and two labels).
I think the problem is somehow connected to the PiSimulator._adjust_sizes function which dynamically changes the font or to the use of the canvas with a columnspan of 2.
Here's my code:
import tkinter as tk
from tkinter import font
class PiSimulator(tk.Frame):
def __init__(self, root, **kwargs):
super(PiSimulator, self).__init__(root, **kwargs)
self.root = root
self.root.title = 'Crtac krugova'
self.root.minsize(width = 600, height = 400)
self.pack(fill = 'both', expand = 1)
self.custom_font = font.Font(size = 20)
self.bind('<Configure>', self._adjust_sizes)
self.populate()
return
def populate(self):
tk.Label(self, text = 'Radijus:', font = self.custom_font, relief = 'raised',\
fg = 'green').grid(sticky='nswe', row = 0, column = 0)
self.radius = tk.IntVar()
tk.Spinbox(self, from_ = 1, to = 16, font = self.custom_font, textvariable = self.radius).grid(row = 1, column = 0)
tk.Label(self, text = 'Greška', font = self.custom_font, relief = 'raised', anchor='w',\
padx = 5, pady = 5, fg = 'green').grid(sticky='nswe', row = 0, column = 1)
self.error = tk.DoubleVar(0.0)
tk.Label(self, textvariable = self.error, font = self.custom_font, relief = 'raised',\
anchor='e', pady = 5, fg = 'green').grid(row = 0, column = 2, sticky='nswe')
self.canvas = PiCanvas(self, highlightthickness = 0)
self.canvas.grid(row = 1, rowspan = 5, column = 1, columnspan = 2, padx = 5, pady = 5, sticky='nswe')
tk.Button(self, text = 'Nacrtaj', font = self.custom_font, command = lambda: self.canvas.draw(self.radius.get())).grid(\
column = 0, row = 2, sticky='nswe')
tk.Button(self, text = 'Izbriši', font = self.custom_font, command = self.canvas.clear ).grid(\
column = 0, row = 3, sticky='nswe')
tk.Label(self, text = 'POVRŠINA', relief = 'groove', font = self.custom_font).grid(column = 0, row = 4, sticky='nswe')
self.area = tk.IntVar(0)
tk.Label(self, textvariable = self.area, relief = 'groove', font = self.custom_font).grid(column = 0, row = 5, sticky='nswe')
for i in range(3):
self.columnconfigure(i, weight = 1)
for i in range(6):
self.rowconfigure(i, weight = 1)
return
def _adjust_sizes(self, event):
new_font = int(event.height/15) - 2
self.custom_font.configure(size = new_font)
return
class PiCanvas(tk.Canvas):
def __init__(self, root, **kwargs):
super(PiCanvas, self).__init__(root, background = 'white', relief = 'groove', **kwargs)
self.root = root
self.cubes = []
self.circle = None
def draw(self, radius):
self.clear()
c_width = self.winfo_width()
c_height = self.winfo_height()
self.grid_side = int(min([c_width, c_height]))
self.grid_side-= 10
self.v_offset = (c_height - self.grid_side)/2
self.h_offset = (c_width - self.grid_side)/2
self.cube_side = self.grid_side/(2*radius)
vertix_coord = lambda x, x_cor, y_cor: x_cor*self.h_offset+y_cor*self.v_offset+x*self.cube_side
for i in range(2*radius):
new_line = []
for j in range(2*radius):
cube = self.create_rectangle(vertix_coord(i, 1, 0), vertix_coord(j, 0, 1),\
vertix_coord(i+1, 1, 0), vertix_coord(j+1, 0, 1), tag = 'unused')
new_line.append(cube)
self.cubes.append(new_line)
self.circle = self.create_oval(vertix_coord(0,1,0), vertix_coord(0,0,1),\
vertix_coord(2*radius,1,0), vertix_coord(2*radius,0,1),width = 2)
self.color_border_cubes()
print(self.circle)
def color_border_cubes(self):
circle_coords = self.coords(self.circle)
print(circle_coords)
for i in self.cubes:
for j in i:
cube_coords = self.coords(j)
if self.circle in self.find_overlapping(*cube_coords) + self.find_enclosed(*circle_coords):
self.itemconfigure(j, fill = 'green')
def clear(self):
self.cubes = []
self.circle = None
self.delete('all')
return
root = tk.Tk()
a=PiSimulator(root)
root.mainloop()

Resources