Why can I not access any variables that I create in this class? I get Control has no attribute setTemp whenever I try to access it. If I declare it outside __init__ I also get an error. For whatever reason, I can't grasp how to properly declare variables in a Python class, then later use them in methods.
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from vivTimer import *
import RPi.GPIO as GPO
import threading
import time
import board
import adafruit_dht
dhtDevice = adafruit_dht.DHT22(board.D4, use_pulseio=False)
class Control(object):
setHumid = 95
timer = 5000
def __init__(self, master):
setTemp = StringVar()
setTemp.set('85')
#set default max temp and humidity
master.title('Vivarium Control')
master.resizable(False, False)
master.configure(background = '#e6e6e6')
self.style = ttk.Style()
self.style.configure('TFrame', background = '#e6e6e6')
self.style.configure('TButton', background = '#e1d8b9')
self.style.configure('TLabel', background = '#e6e6e6', font = ('Arial', 11))
self.style.configure('Header.TLabel', font = ('Arial', 18, 'bold'))
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
self.logo = PhotoImage(file = '115500-200.png')
ttk.Label(self.frame_header, image = self.logo).grid(row = 0, column = 0, rowspan = 2)
ttk.Label(self.frame_header, text = 'Vivarium Controller', style = 'Header.TLabel').grid(row = 0, column = 1)
ttk.Label(self.frame_header, wraplength = 300,
text = ("Temperature and Humidity control. "
"Enter maximums for both humidity and temperature.")).grid(row = 1, column = 1, padx = 5, sticky = 'nw')
self.frame_content = ttk.Frame(master)
self.frame_content.pack()
ttk.Label(self.frame_content, text = 'Maximum Temp:').grid(row = 0, column = 0, padx = 5, sticky = 'sw')
ttk.Label(self.frame_content, text = 'Maximum Humidity:').grid(row = 0, column = 1, padx = 5, sticky = 'sw')
self.setTempL = Label(self.frame_content, textvariable = setTemp).grid(row = 0, column = 3, padx = 5, sticky = 'sw')
ttk.Label(self.frame_content, text = 'Current Humidity:' + str(self.setHumid)).grid(row = 0, column = 4, padx = 5, sticky = 'sw')
self.entry_temp = ttk.Entry(self.frame_content, textvariable = setTemp, width = 10, font = ('Arial', 10))
self.entry_humid = ttk.Entry(self.frame_content, width = 10, font = ('Arial', 10))
self.entry_temp.grid(row = 1, column = 0, padx = 5)
self.entry_humid.grid(row = 1, column = 1, padx = 5)
ttk.Button(self.frame_content, text = 'Save',
command = self.save).grid(row = 4, column = 0, padx = 5, pady = 5, sticky = 'e')
def updateLabels(self):
print('blah')
def createTimer(root):
print('timer 1 sec')
readTemp = False
while readTemp == False:
try:
# Print the values to the serial port
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
print(
"Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(
temperature_f, temperature_c, humidity
)
)
readTemp = True
if(temperature_f > int(Control.setTemp.get())):
print('fan on')
except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
dhtDevice.exit()
raise error
time.sleep(2.0)
print(Control.timer)
root.after(Control.timer, Control.createTimer, root)
#t2 = threading.Thread(target=VivTimer.startTimer(), args=(10,))
#t2.start()
def save(self):
tempT = self.entry_temp.get()
self.setTemp = tempT
print(self.setTemp)
self.setHumid = self.entry_humid.get()
Control.updateLabels(self)
print('Temp: {}'.format(self.entry_temp.get()))
print('Humidity: {}'.format(self.entry_humid.get()))
self.clear()
messagebox.showinfo(title = 'Vivarium Control', message = 'Conditions saved!')
def clear(self):
self.entry_temp.delete(0, 'end')
self.entry_humid.delete(0, 'end')
def main():
root = Tk()
control = Control(root)
root.after(1000, Control.createTimer, root)
root.mainloop()
if __name__ == "__main__": main()
I think the following modified version of your code will work much better if you undo all the places I commented out your code (and usually put in a replacement below it). This was necessary to make it possible to run the code at all for testing since I don't have your hardware (or the one image file).
You will need to undo them to try it with your hardware.
The two most significant changes I made were turning setTemp into a class instance attribute and modifying createTimer() to make it a proper class method.
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
#from vivTimer import *
#import RPi.GPIO as GPO
import time
#import board
#import adafruit_dht
#
#dhtDevice = adafruit_dht.DHT22(board.D4, use_pulseio=False)
class Control(object):
setHumid = 95
timer = 5000
def __init__(self, master):
self.setTemp = StringVar()
self.setTemp.set('85')
#set default max temp and humidity
master.title('Vivarium Control')
master.resizable(False, False)
master.configure(background = '#e6e6e6')
self.style = ttk.Style()
self.style.configure('TFrame', background = '#e6e6e6')
self.style.configure('TButton', background = '#e1d8b9')
self.style.configure('TLabel', background = '#e6e6e6', font = ('Arial', 11))
self.style.configure('Header.TLabel', font = ('Arial', 18, 'bold'))
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
# self.logo = PhotoImage(file = '115500-200.png')
self.logo = PhotoImage(file = '8-ball.png')
ttk.Label(self.frame_header, image = self.logo).grid(row = 0, column = 0, rowspan = 2)
ttk.Label(self.frame_header, text = 'Vivarium Controller', style = 'Header.TLabel').grid(row = 0, column = 1)
ttk.Label(self.frame_header, wraplength = 300,
text = ("Temperature and Humidity control. "
"Enter maximums for both humidity and temperature.")).grid(row = 1, column = 1, padx = 5, sticky = 'nw')
self.frame_content = ttk.Frame(master)
self.frame_content.pack()
ttk.Label(self.frame_content, text = 'Maximum Temp:').grid(row = 0, column = 0, padx = 5, sticky = 'sw')
ttk.Label(self.frame_content, text = 'Maximum Humidity:').grid(row = 0, column = 1, padx = 5, sticky = 'sw')
self.setTempL = Label(self.frame_content, textvariable=self.setTemp).grid(row = 0, column = 3, padx = 5, sticky = 'sw')
ttk.Label(self.frame_content, text = 'Current Humidity:' + str(self.setHumid)).grid(row = 0, column = 4, padx = 5, sticky = 'sw')
self.entry_temp = ttk.Entry(self.frame_content, textvariable=self.setTemp, width = 10, font = ('Arial', 10))
self.entry_humid = ttk.Entry(self.frame_content, width = 10, font = ('Arial', 10))
self.entry_temp.grid(row = 1, column = 0, padx = 5)
self.entry_humid.grid(row = 1, column = 1, padx = 5)
ttk.Button(self.frame_content, text = 'Save',
command = self.save).grid(row = 4, column = 0, padx = 5, pady = 5, sticky = 'e')
def updateLabels(self):
print('blah')
def createTimer(self, root):
print('timer 1 sec')
readTemp = False
while readTemp == False:
try:
# Print the values to the serial port
# temperature_c = dhtDevice.temperature
temperature_c = 30
temperature_f = temperature_c * (9 / 5) + 32
# humidity = dhtDevice.humidity
humidity = 20
print(
"Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(
temperature_f, temperature_c, humidity
)
)
readTemp = True
if(temperature_f > int(self.setTemp.get())):
print('fan on')
except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
# dhtDevice.exit()
raise error
time.sleep(2.0)
print(Control.timer)
root.after(Control.timer, self.createTimer, root)
def save(self):
tempT = self.entry_temp.get()
self.setTemp = tempT
print(self.setTemp)
self.setHumid = self.entry_humid.get()
Control.updateLabels(self)
print('Temp: {}'.format(self.entry_temp.get()))
print('Humidity: {}'.format(self.entry_humid.get()))
self.clear()
messagebox.showinfo(title = 'Vivarium Control', message = 'Conditions saved!')
def clear(self):
self.entry_temp.delete(0, 'end')
self.entry_humid.delete(0, 'end')
def main():
root = Tk()
control = Control(root)
root.after(1000, control.createTimer, root)
root.mainloop()
if __name__ == "__main__":
main()
Related
I have a problem regarding tkinter's grid_forget() method. I have 2 pages in a notebook and I want to show certain widgets on the second page based off the user's selected options in the first page, I have a multiple choice menu and the grid_forget() method seems to work well until I select 2 or more options from the menu. I tried creating the widgets when an option is selected and place them based on the choice, no luck there, also tried creating them with the rest of the widgets and when the user selected an option I would simply just use grid to place them on the screen, also no luck there. I created a demo below, sorry for potential mistakes.
import tkinter as tk
from tkinter import ttk
SMALL_FONT = ("calibri", 16)
class App(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.notebook = ttk.Notebook(self, height = "900", width = "1600")
self.notebook.grid(row = 0, column = 0)
self.frame_pasul3 = tk.Frame(self.notebook)
self.frame_pasul1 = tk.Frame(self.notebook)
self.notebook.add(self.frame_pasul1, text = "First page")
self.notebook.add(self.frame_pasul3, text = "Second page")
self.first_page()
def first_page(self):
options = ["Urmarire mobiliara",
"Urmarire imobiliara",
"Predarea silita bunuri imobile",
"Predarea silita bunuri mobile",
"Obligatia de a face",
"Executare minori"]
menubutton_modalitate_exec = tk.Menubutton(self.frame_pasul1, text="Alegeti o modalitate de executare",
indicatoron=True, borderwidth=1, fg = "#000000",relief="raised")
menu_modalitate_exec = tk.Menu(menubutton_modalitate_exec, tearoff=False)
menubutton_modalitate_exec.configure(menu=menu_modalitate_exec)
menubutton_modalitate_exec.grid(row = 4, column = 1)
self.modalitate = {}
for choice in options:
self.modalitate[choice] = tk.StringVar()
menu_modalitate_exec.add_checkbutton(label=choice, variable=self.modalitate[choice],
onvalue=1, offvalue=0,
command=self.printValues)
self.second_page()
def second_page(self):
self.frame3_titlu_exec = ttk.Frame(self.frame_pasul3)
self.frame3_titlu_exec.grid()
self.frame3_text = ttk.Frame(self.frame_pasul3)
self.frame3_text.grid()
self.frame3_creante = tk.Frame(self.frame_pasul3)
self.frame3_creante.grid()
self.frame3_reprezentand_obligatia = tk.Frame(self.frame_pasul3)
self.frame3_judecatorie = ttk.Frame(self.frame_pasul3)
self.frame3_judecatorie.grid()
self.frame3_texte = tk.Frame(self.frame_pasul3)
self.frame3_texte.grid()
ttk.Label(self.frame3_titlu_exec, font = SMALL_FONT, text = "Titlu Executoriu").grid(row = 0, column = 0, columnspan = 4 ,pady = 10)
ttk.Button(self.frame3_titlu_exec, text = "Contract de credit.").grid(row = 1, column = 0, padx = 10, ipadx = 15, ipady = 5)
ttk.Button(self.frame3_titlu_exec, text = "Sentinta civila.").grid(row = 1, column = 1, padx = 10, ipadx = 15, ipady = 5)
ttk.Button(self.frame3_titlu_exec, text = "Contract notarial.").grid(row = 1, column = 2,padx = 10, ipadx = 15, ipady = 5)
ttk.Button(self.frame3_titlu_exec, text = "Act de adjudecare.").grid(row = 1, column = 3, padx = 10, ipadx = 15, ipady = 5)
self.entry = tk.Text(self.frame3_text, height = 2, wrap = "word", font = ("Helvetica", 10))
self.entry.grid(row = 0, column = 1, padx = 10, pady = 15)
ttk.Button(self.frame3_text, text = "Incarca titlu").grid(row = 0, column = 2, padx = 10, pady = 15)
ttk.Label(self.frame3_creante, font = SMALL_FONT, text = "Creante").grid(row = 0, column = 0)
self.btn_adauga_creante = ttk.Button(self.frame3_creante, text = "Adauga")
self.btn_adauga_creante.grid(row = 0, column = 3)
self.reprezentand_fapt_label = ttk.Label(self.frame3_judecatorie, font = SMALL_FONT, text = "Ce reprezinta fapta.")
self.reprezentand_fapt_label.grid(row = 2, column = 1)
self.reprezentand_creante = tk.Text(self.frame3_judecatorie, height = 3, width = 70)
self.reprezentand_creante.grid(row = 3 , column = 1, pady = 15)
ttk.Label(self.frame3_texte, font = SMALL_FONT, text = "Judecatorie").grid(row = 4, column = 1)
options_jud = ["optiunea 2.",
"test 3",
"test 4",
"test 5"]
self.judecatorie = ttk.Combobox(self.frame3_texte, values = options_jud)
self.judecatorie.set("Selecteaza o judecatorie.")
self.judecatorie.grid(row = 5, column = 1)
ttk.Button(self.frame3_texte, text = "Pasul 2. Parti dosar.").grid(row = 6, column = 0, padx = 15, ipadx = 15, ipady = 5)
ttk.Button(self.frame3_texte, text = "Pasul 4. Cheltuieli de executare").grid(row = 6, column = 3, ipadx = 15, ipady = 5)
def printValues(self):
for name, var in self.modalitate.items():
if var.get() == "1" and (name == "Predarea silita bunuri imobile" or name == "Predarea silita bunuri mobile" or name == "Obligatia de a face" or name == "Executare minori"):
self.reprezentand_creante_label = tk.Label(self.frame3_judecatorie, font = SMALL_FONT, text = "Ce reprezinta creanta.")
self.reprezentand_creante = tk.Text(self.frame3_judecatorie, wrap = "word", height = 3, width = 70)
self.ok_modalitate_exec = 1
self.reprezentand_creante_label.grid(row = 0, column = 1, padx = 15, pady = 15)
self.reprezentand_creante.grid(row = 1, column = 1, padx = 15, pady = 15)
print("Avem 1 la cele 4", name, var.get())
break
elif var.get() == "0" and (name == "Predarea silita bunuri imobile" or name == "Predarea silita bunuri mobile" or name == "Obligatia de a face" or name == "Executare minori"):
print("Avem 0 la cele 4", name, var.get())
self.ok_modalitate_exec = 0
self.reprezentand_creante_label.grid_forget()
self.reprezentand_creante.grid_forget()
break
if __name__ == "__main__":
main_window = tk.Tk()
app = App(main_window)
app.grid()
main_window.mainloop()
i want it to expand the size accordingly if the window is expanded, so far i use the grid.row/column configure to make its weight =1 but it will be all messed up it i expand the window.
import time
import tkinter as tk
#Initialise the window
clock = tk.Tk()
clock.title('Easy CLock')
clock.configure(bg='#121212')
clock.columnconfigure(0, weight = 1)
clock.rowconfigure(0, weight = 1)
border_effects = {
"flat": tk.FLAT,
"sunken": tk.SUNKEN,
"raised": tk.RAISED,
"groove": tk.GROOVE,
"ridge": tk.RIDGE,
}
#Logo will be under the main parent
logo = tk.PhotoImage(file = r'C:\Users\User\VSC\Alarm\Logo1.png')
logo_size = logo.subsample(5)
#Time and Date function
def time_date():
# current time
current_time = time.strftime('%H:%M:%S')
current_date = time.strftime(r'%m/%d/%Y')
clock.after(200, time_date)
#Displays the time
c_time = tk.Label(f_time, text = current_time, fg='white', bg='#121212', font=('Verdana', 30))
c_date = tk.Label(f_time, text = current_date, font=('Verdana', 10), fg='white', bg='#121212')
c_time.grid(column=0, row=0)
c_date.grid(column=0, row=1)
#alarm button command
def alarm_func():
#Alarm label
c_clicked = tk.Label(f_alarm, text='Alarm Interface', fg='white', bg='#121212')
c_clicked.grid(column=0, row=1, sticky = 'N')
def recall_frame(event):
if event == f_alarm:
event.grid_forget()
f_time.grid(column=0, row =1, columnspan = 4, sticky = 'N')
elif event == f_time:
event.grid_forget()
f_alarm.grid(column=0, row=1, columnspan = 4, rowspan = 2)
def back_func():
pass
#Creating Frames
f_time = tk.Frame(clock) #Clock Button
f_alarm = tk.Frame(clock) #Alarm Buttton
#configure the frames
f_time.configure(bg = '#121212')
f_alarm.configure(bg = '#121212')
#Setting label in the frame
f_lbl = tk.Label(clock, text= ' Simplistic Clock', image = logo_size, font=('Verdana', 30), fg='white', bg='#121212', compound = tk.LEFT)
time_but = tk.Button(clock, text='Clock', command= lambda :[time_date(), recall_frame(f_alarm)], bg='#f39c12', width = 15, relief = border_effects['ridge'])
alarm_but = tk.Button(clock, text = 'Alarm', command = lambda :[alarm_func(), recall_frame(f_time)], bg='#f39c12', width = 15, relief = border_effects['ridge'])
quit_but = tk.Button(clock, text='Exit', command = clock.quit, bg='#f39c12', width = 15, relief = border_effects['ridge'])
back_but = tk.Button(clock, text = 'Back To Home', command = back_func, bg='#f39c12', width = 15, relief = border_effects['ridge'])
f_lbl.config(borderwidth = 4, relief = border_effects['sunken'])
f_lbl.grid_columnconfigure(0, weight = 1)
#Putting it on the frames
f_lbl.grid(column = 0, row = 0, columnspan = 4, sticky = 'N')
time_but.grid(column = 0, row = 3)
alarm_but.grid(column = 1, row = 3)
back_but.grid(column = 2, row = 3)
quit_but.grid(column = 3, row = 3)
clock.mainloop()
also, why does the border in the f_lbl, simplistic clock not fully extended through out all 4 column since i put columnspan = 4 , and weight = 1 , should't it expand fully through all 4 columns?
Good afternoon,
I've been trying for two days to solve this problem and desperate, I am looking for your help. I want to show a plot (using matplotlib) within my tkinter application (not opening it in a different window) and the problem is that when I press any of the toolbar buttons as soon as I cross with the mouse coursor the lines of the plot, the plot disappears for a brief moment and appears again, but the toolbar buttons disappear until I cross them again with the mouse coursor. So for the button to appear back I should cross it and cross out off the button.
I noticed that if I change the background image (just the color, placed in label) the disappeared buttons are replaced with that color, so it seems that when I cross the lines of the plot everything in the Label except the plot is overlayed by the background.
Regards,
Wladyslaw
The code is:
import tkinter as tk
from tkinter.ttk import *
from tkinter import *
import tkinter.font as tkFont
from tkinter import scrolledtext
import logging
from PIL import Image, ImageTk
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import numpy as np
from matplotlib.figure import Figure
import numpy as np
import sys
if sys.version_info[0] < 3:
import Tkinter as tk
else:
import tkinter as tk
from matplotlib.backends import _backend_tk
from matplotlib.backends.backend_agg import FigureCanvasAgg
class WidgetLogger(logging.Handler):
def __init__(self, widget):
logging.Handler.__init__(self)
self.setLevel(logging.INFO)
self.widget = widget
self.widget.config(state='disabled')
def emit(self, record):
self.widget.config(state='normal')
# Append message (record) to the widget
self.widget.insert(tk.END, self.format(record) + '\n')
self.widget.see(tk.END) # Scroll to the bottom
self.widget.config(state='disabled')
class Product:
def __init__(self, window):
self.wind = window
self.wind.geometry("1060x700")
self.wind.title('Artificial intelligence based pricer')
self.wind.lift()
#self.wind.resizable(width=False, height=False)
background_color = '#526b70'
background_color2 = '#e4e8eb'
background_color3 = '#e4e8eb'
background_color4 = '#c4cfd2'
text_color = 'white'
style = ttk.Style()
style.configure("TProgressbar", background=background_color)
img = Image.open('Files/Images/background_image.jpg')
img = ImageTk.PhotoImage(img)
background = tk.Label(self.wind, image=img, bd=0)
background.grid(row = 0, column = 0, rowspan = 8, columnspan = 5)
background.image = img
img2 = Image.open('Files/Images/background_image2.jpg')
img2 = ImageTk.PhotoImage(img2)
background2 = tk.Label(self.wind, image=img2, bd=0)
background2.grid(row = 9, column = 0, rowspan = 10, columnspan = 10)
background2.image = img2
########## LEFT TOP SIDE ##############################
fontStyleTitle = tkFont.Font(family="Times New Roman (Times)", size=12, weight='bold')
fontStyleText = tkFont.Font(family="Arial", size=10, weight='bold')
Label1 = Label(background, text = ' ')
Label1.grid(row = 0, column = 0)
Label1.configure(background=background_color)
Label2 = Label(background, text = 'GLOBAL CONFIGURATION', fg=text_color, font=fontStyleTitle)
Label2.grid(row = 1, column = 1, padx = 3, columnspan = 2, sticky = W)
Label2.configure(background=background_color)
Label3 = Label(background, text = 'Shop ID: ', fg=text_color, font=fontStyleText)
Label3.grid(row = 2, column = 1, pady = 4, sticky = W)
Label3.configure(background=background_color)
self.shop = Entry(background)
self.shop.focus()
self.shop.grid(row = 2, column = 2)
self.shop.configure(background=background_color3)
Label4 = Label(background, text = 'Item ID: ', fg=text_color, font=fontStyleText)
Label4.grid(row = 3, column = 1, sticky = W)
Label4.configure(background=background_color)
self.item = Entry(background)
self.item.grid(row = 3, column = 2)
self.item.configure(background=background_color3)
Label5 = Label(background, text = '')
Label5.grid(row = 4, column = 1)
Label5.configure(background=background_color)
Label6 = Label(background, text = 'ANN CONFIGURATION', font = fontStyleTitle, fg=text_color)
Label6.grid(row = 5, column = 1, padx = 3, columnspan = 2, sticky = W)
Label6.configure(background=background_color)
Label7 = Label(background, text = 'Model: ', fg=text_color, font=fontStyleText)
Label7.grid(row = 6, column = 1, pady = 4, sticky = W)
Label7.configure(background=background_color)
self.model = Entry(background)
self.model.grid(row = 6, column = 2)
self.model.configure(background=background_color3)
Label8 = Label(background, text = 'Test set: ', fg=text_color, font=fontStyleText)
Label8.grid(row = 7, column = 1, sticky = W)
Label8.configure(background=background_color)
self.test_set = Entry(background)
self.test_set.grid(row = 7, column = 2)
self.test_set.configure(background=background_color3)
Button1 = tk.Button(background, bg=background_color2, text = 'Calculate performance')
Button1.grid(row = 8, column = 1, padx = 50, pady = 10, columnspan = 2, sticky = W+E)
#Button1.configure(background=background_color)
########## CENTER TOP SIDE ############################
Label9 = Label(background, text = 'ANN MODEL PERFORMANCE', font=fontStyleTitle, fg=text_color)
Label9.grid(row = 1, column = 3, padx = 40, sticky = W)
Label9.configure(background=background_color)
performace = Text(background, height=8, width=50)
performace.grid(row = 2, column = 3, padx = 40, rowspan = 6)
temporalText = '''MSE of standarized mean predictions: 700,5496
MSE of standarized ANN predictions: 700,5496
MSE of deseasonalized mean predictions: 700,5496
MSE of deseasonalized ANN predictions: 700,5496
MSE of seasonalized mean predictions: 700,5496
MSE of seasonalized ANN predictions: 700,5496'''
performace.insert(tk.END, temporalText)
performace.configure(background=background_color3)
Widget_Logger = WidgetLogger(performace)
progress = Progressbar(background, style='TProgressbar', orient = HORIZONTAL, length = 100, mode = 'determinate')
progress.grid(row = 8, column = 3, padx = 40, sticky = W+E)
#progress.configure(background=background_color)
########## RIGHT TOP SIDE #############################
Label10 = Label(background, text = ' ')
Label10.grid(row = 0, column = 6)
Label10.configure(background=background_color)
Label11 = Label(background, text = "PREDICTION'S CONFIGURATION", font=fontStyleTitle, fg=text_color)
Label11.grid(row = 1, column = 4, padx = 3, columnspan = 2, sticky = W)
Label11.configure(background=background_color)
Label12 = Label(background, text = 'Precision: ', fg=text_color, font=fontStyleText)
Label12.grid(row = 2, column = 4, pady = 4, sticky = W)
Label12.configure(background=background_color)
self.precision = Entry(background)
self.precision.focus()
self.precision.grid(row = 2, column = 5)
self.precision.configure(background=background_color3)
Label13 = Label(background, text = 'Max. price multiplicator: ', fg=text_color, font=fontStyleText)
Label13.grid(row = 3, column = 4, sticky = W)
Label13.configure(background=background_color)
self.max_price_multiplicator = Entry(background)
self.max_price_multiplicator.grid(row = 3, column = 5)
self.max_price_multiplicator.configure(background=background_color3)
Label14 = Label(background, text = 'Delta multiplicator: ', fg=text_color, font=fontStyleText)
Label14.grid(row = 4, column = 4, pady = 4, sticky = W)
Label14.configure(background=background_color)
self.delta_multiplicator = Entry(background)
self.delta_multiplicator.grid(row = 4, column = 5)
self.delta_multiplicator.configure(background=background_color3)
Label15 = Label(background, text = 'Item cost: ', fg=text_color, font=fontStyleText)
Label15.grid(row = 5, column = 4, sticky = W)
Label15.configure(background=background_color)
self.item_cost = Entry(background)
self.item_cost.grid(row = 5, column = 5)
self.item_cost.configure(background=background_color3)
Radiobutton(background, text = "absolute", variable = (background,"1"), value = "1", indicator = 0, background = "light blue", activebackground=background_color2, activeforeground='black').grid(row = 6, column = 4, sticky = E)
Radiobutton(background, text = "mean price multiplicator", variable = (background,"1"), value = "2", indicator = 0, background = "light blue", activebackground=background_color2, activeforeground='black').grid(row = 6, column = 5, pady = 4, sticky = W)
Label16 = Label(background, text = 'Fixed costs: ', fg=text_color, font=fontStyleText)
Label16.grid(row = 7, column = 4, sticky = W)
Label16.configure(background=background_color)
self.fixed_costs = Entry(background)
self.fixed_costs.grid(row = 7, column = 5)
self.fixed_costs.configure(background=background_color3)
Button2 = tk.Button(background, bg=background_color2, text = 'Calculate predictions')
Button2.grid(row = 8, column = 4, padx = 80, pady = 10, columnspan = 2, sticky = W+E)
Label17 = Label(background, text = ' ')
Label17.grid(row = 0, column = 6, sticky = W)
Label17.configure(background=background_color)
########## LEFT BOTTOM SIDE ###########################
Label18 = Label(background, text = ' ')
Label18.grid(row = 9, column = 1)
Label18.configure(background=background_color)
fig = Figure(figsize=(6, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
canvas = FigureCanvasTkAgg(fig, master=background2)
canvas.draw()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
toolbarFrame = Frame(master=background2)
toolbarFrame.pack(side=TOP, fill=BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, toolbarFrame)
toolbar.update()
canvas.mpl_connect("key_press_event", on_key_press)
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
if __name__ == '__main__':
window = Tk()
application = Product(window)
window.mainloop()```
I'm working on my final project for my computing I class.
The problem that I am having is:
When I click on the new entry button, hit the back button and click on the new entry button once again it does not work.
If you guys could tell me why that is?
The command on the button seems to be only working once. Thanks for your help.
Code:
from tkinter import *
import tkinter.filedialog
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.title("Entry Sheet")
self.font = ("Helvetica","13")
self.header_font = ("Helvetica","18")
self.exercise_font = ("Helvetica","13","bold")
self.delete = 'a'
self.new_user()
def new_user(self):
if self.delete == 'b':
self.delete = 'c'
self.hide()
self.delete = 'b'
self.new_entry = Button(self, text = 'New Entry', command = self.entry, width = 15)
self.new_entry.grid(row = 1, column = 0, columnspan = 3, padx = 10, pady = 5)
self.look_entry = Button(self, text = 'See Entries', command = self.see_entries, width = 15)
self.look_entry.grid(row = 2, column =0, columnspan = 3, padx = 10, pady = 5)
def entry(self):
print(1)
self.delete = 'b'
self.hide()
self.entry = Label(self, text = 'New Entry', font = self.header_font)
self.entry.grid(row = 0, column = 0, columnspan = 2)
self.numberlbl = Label(self, text = 'Please choose a muscle?', font = self.font)
self.numberlbl.grid(row = 1, column= 0, columnspan = 2, sticky = 'w' )
self.muscle_chosen = IntVar()
self.chest = Radiobutton(self, text = "chest", variable = self.muscle_chosen, value = 1, font = self.font)
self.bicep = Radiobutton(self, text = "bicep", variable = self.muscle_chosen, value = 2, font = self.font)
self.chest.grid(row = 2, column = 0)
self.bicep.grid(row = 2, column = 1)
self.exerciseslbl = Label(self, text = 'Please enter the number of exercises: ', font = self.font)
self.exerciseslbl.grid(row = 3, column = 0, columnspan = 3)
self.exercises_spinbox = Spinbox(self, from_= 1, to_= 50, width = 5, font = self.font)
self.exercises_spinbox.grid(row = 4, column = 0)
self.back_button = Button(self, text = 'Back', command = self.new_user, width = 10)
self.back_button.grid(row =5, column=0, pady =10)
def see_entries(self):
print("Goes through")
def hide(self):
if self.delete == 'b':
self.new_entry.grid_remove()
self.look_entry.grid_remove()
elif self.delete == 'c':
self.entry.grid_remove()
self.numberlbl.grid_remove()
self.chest.grid_remove()
self.bicep.grid_remove()
self.exerciseslbl.grid_remove()
self.exercises_spinbox.grid_remove()
self.back_button.grid_remove()
def main():
app = App()
app.mainloop()
if __name__=="__main__":
main()
In your entry function you overwrite self.entry, which is the name of the function, with a reference to a Label. When the button then calls self.entry it isn't function.
Simply call the Label something else.
I am trying to calculate a formula and display its output as a table in TKinter. Since it is not working, I am just trying to get a simple result and print it to a canvas widget. When this gets working I will do the entire loan formula. As it is I get no output in the GUI or in the console.
Is this even possible to place the result of a calculation as text in canvas.create_text?
from tkinter import * # Import tkinter
width = 500
height = 500
class MainGUI:
def __init__(self):
window = Tk() # Create a window
window.title(" Loan Schedule ") # Set title
frame1 = Frame(window)
frame1.grid(row = 1, column = 1)
Label(frame1, text = " Loan Amount ").grid(row = 1, column = 1, sticky = W)
self.v1 = StringVar()
Entry(frame1, textvariable = self.v1, justify = RIGHT).grid(row = 1, column = 2)
Label(frame1, text = " Years ").grid(row = 1, column = 3, sticky = W)
self.v2 = StringVar()
Entry(frame1, textvariable = self.v2, justify = RIGHT).grid(row = 1, column = 4)
btCalculate = Button(frame1, text = " Calculate ", command = self.calculate()).grid(row = 1, column = 5, sticky = E)
frame2 = Frame(window)
frame2.grid(row = 2, column = 1)
self.canvas = Canvas(frame2, width = width, height = height, bg = "white")
self.canvas.pack()
self.canvas.create_text(25, 25, text = self.calculate(), tags = "text")
window.mainloop() # Create an event loop
def calculate(self):
result = self.v1.get() + self.v2.get()
print(result)
return result
MainGUI()
command require function name without ()
command = self.calculate
so now it works
from tkinter import * # Import tkinter
width = 500
height = 500
class MainGUI:
def __init__(self):
window = Tk() # Create a window
window.title(" Loan Schedule ") # Set title
frame1 = Frame(window)
frame1.grid(row = 1, column = 1)
Label(frame1, text = " Loan Amount ").grid(row = 1, column = 1, sticky = W)
self.v1 = StringVar()
Entry(frame1, textvariable = self.v1, justify = RIGHT).grid(row = 1, column = 2)
Label(frame1, text = " Years ").grid(row = 1, column = 3, sticky = W)
self.v2 = StringVar()
Entry(frame1, textvariable = self.v2, justify = RIGHT).grid(row = 1, column = 4)
btCalculate = Button(frame1, text = " Calculate ", command = self.calculate).grid(row = 1, column = 5, sticky = E)
frame2 = Frame(window)
frame2.grid(row = 2, column = 1)
self.canvas = Canvas(frame2, width = width, height = height, bg = "white")
self.canvas.pack()
self.canvas.create_text(55, 10, text = self.add_text(), tags = "text")
window.mainloop() # Create an event loop
def calculate(self):
result = int(self.v1.get()) + int(self.v2.get())
self.canvas.create_text(25, 25, text = result, tags = "text")
print(result)
return result
def add_text(self):
return "HELLO WORLD"
MainGUI()
by the way: line below means - run self.calculate() and result assign to command
command = self.calculate()