I made small medical calculator program for python learning.
In this program, when i press "Calc" button, it should be displayed in my command line. But it doesn't work.
Moreover, I suspect that the defined function is operated without button click.
What do i have a mistake?
#importing modules
from tkinter import *
#setting up window
top = Tk()
F = Frame(top)
F.master.title("FeNa Calculator")
F.pack()
#Calc. button event handler
def fena_click():
ur_na = tUNa.get()
ur_cr = tUCr.get()
se_na = tSNa.get()
se_cr = tSCr.get()
print('Urine Na : ' + ur_na, end=' ')
print('Urine Cr : ' + ur_cr, end=' ')
print('Serum Na : ' + se_na, end=' ')
print('Serum Cr : ' + se_cr, end=' ')
#add widgets
unit1 = Label(F, text="mEq/L")
unit2 = Label(F, text="mEq/L")
unit3 = Label(F, text="mEq/L")
unit4 = Label(F, text="mEq/L")
UNa = Label(F, text="Urine Na")
tUNa = Entry(F)
UCr = Label(F, text="Urine Cr")
tUCr = Entry(F)
SNa = Label(F, text="Serum Na")
tSNa = Entry(F)
SCr = Label(F, text="Serum Cr")
tSCr = Entry(F)
blank1 = Label(F, text="")
v_Result = StringVar()
Result = Label(F, textvariable = v_Result)
v_Result.set("FENa(%) = ")
blank2 = Label(F, text="")
bCalc = Button(F, text="Calc.", command = fena_click())
bQuit = Button(F, text="Quit", command = F.quit)
UNa.grid(row = 0, column = 0, pady = 2)
tUNa.grid(row =0, column = 1, pady = 2)
unit1.grid(row = 0, column = 2, pady = 2)
UCr.grid(row = 1, column = 0, pady = 2)
tUCr.grid(row =1, column = 1, pady = 2)
unit2.grid(row = 1, column = 2, pady = 2)
SNa.grid(row = 2, column = 0, pady = 2)
tSNa.grid(row =2, column = 1, pady = 2)
unit3.grid(row = 2, column = 2, pady = 2)
SCr.grid(row = 3, column = 0, pady = 2)
tSCr.grid(row =3, column = 1, pady = 2)
unit4.grid(row = 3, column = 2, pady = 2)
blank1.grid(row=4, column = 0, columnspan = 3)
Result.grid(row = 5, column = 0, columnspan = 3)
blank2.grid(row=6, column = 0, columnspan = 3)
bCalc.grid(row = 7, column = 0, columnspan = 2)
bQuit.grid(row = 7, column = 1, columnspan = 2)
#loop running
F.mainloop()
Program view
In the line where you're making the button, you are actually calling the fena_click function. You need to pass the function itself, which you can do by omitting the paranthesis:
bCalc = Button(F, text="Calc.", command = fena_click) # no () after fena_click
Related
Hey I would like to create a frame which contains a Listbox and some buttons. What I would like to do is to somehow pass as an argument a name of this listbox. This is my current code in which I set the name of this listbox to master.thisListbox but I would like to pass it somehow as argument. Is it possible or should I separately crate a listbox in my App and the pass it as an argument to a frame? I'm going to create a lot of such listboxes in my App hence the name of listbox shouldn't be the same. I'm pretty new in OOP.
class myApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.dateFrame = DateFrame(self)
self.dateFrame.grid(row = 0, column = 0)
print(self.day.get())
self.myFrame = ListboxFrame(self, "Label!", [1,2,3])
self.myFrame.grid(row = 1, column = 0)
x = self.thisListbox.get(0, END)
print(x)
class DateFrame(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
# Day
ttk.Label(self, text = "Day", width = 4).grid(row = 0, column = 0, padx = 3, pady = 3)
master.day = IntVar(master, value = 31)
self.dayCB = ttk.Combobox(self, values = [x for x in range(1, 32)], textvariable = master.day, width = 4)
self.dayCB.grid(row = 1, column = 0, padx = 3, pady = 3)
# Month
ttk.Label(self, text = "Month", width = 6).grid(row = 0, column = 1, padx = 3, pady = 3)
self.month = IntVar(master, value = 12)
self.monthCB = ttk.Combobox(self, values = [x for x in range(1, 13)], textvariable = self.month, width = 4)
self.monthCB.grid(row = 1, column = 1, padx = 3, pady = 3)
# Year
ttk.Label(self, text = "Year", width = 4).grid(row = 0, column = 2, padx = 3, pady = 3)
self.year = IntVar(master, value = 2021)
self.yearCB = ttk.Spinbox(self, from_ = 2020, to = 2100, textvariable = self.year, width = 6)
self.yearCB.grid(row = 1, column = 2, padx = 3, pady = 3)
class ListboxFrame(ttk.Frame):
def __init__(self, master, labelText, values, selectmode = "extended", height = 6, width = 30):
ttk.Frame.__init__(self, master)
# Listbox
ttk.Label(self, text = labelText).grid(row = 0, column = 0, columnspan = 3)
master.thisListbox = tk.Listbox(self, selectmode = selectmode, height = height, width = width)
master.thisListbox.grid(row = 1, column = 0, columnspan = 3, padx = 2, pady = 2)
# Entry
self.entry = ttk.Entry(self)
self.entry.grid(row = 2, column = 0, padx = 2, pady = 2)
# Buttons
self.addButton = ttk.Button(self, text = "Add", width = 4, command = self.Add)
self.addButton.grid(row = 2, column = 1, padx = 2, pady = 2)
self.deleteButton = ttk.Button(self, text = "Delete", width = 6, command = self.Delete)
self.deleteButton.grid(row = 2, column = 2, padx = 2, pady = 2)
for v in values:
master.thisListbox.insert(END, v)
def Add(self):
if self.entry.get() == "": return
master.thisListbox.insert(END, self.entry.get())
self.entry.delete(0, END)
def Delete(self):
for index in reversed(master.thisListbox.curselection()):
master.thisListbox.delete(index)
# listbox.config(height = listbox.size())
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'm trying to create an app that has 2 windows. The first window (A) is only called the first time the app is ran, and then opens window (B). For all future events, only window (B) is called. This is the following code:
# Script Counter/Setup
def read_counter():
if path.exists("counter.json"):
return loads(open("counter.json", "r").read()) + 1
else:
info = tk.Tk()
info.title("Setup")
info.geometry("350x120")
info.grid_columnconfigure((0, 2), weight = 1)
count = tk.Label(info, text = "Previous Post Number")
string = tk.StringVar()
count_input = tk.Entry(info, textvariable = string)
val = string.get()
def destroy_get():
val = int(count_input.get())
info.quit()
return val
count_button = tk.Button(info, text = "Done!", command = destroy_get)
tk.Label(info, text = "Setup", font='Helvetica 18 bold').grid(row = 0, column = 1, padx = 5, pady = 5)
count.grid(row = 1, column = 0, padx = 5, pady = 5)
count_input.grid(row = 1, column = 2, padx = 5, pady = 5)
count_button.grid(row = 2, column = 1, padx = 5, pady = 5)
info.mainloop()
# info.destroy()
return destroy_get()
def write_counter():
with open("counter.json", "w") as f:
f.write(dumps(counter))
counter = read_counter()
atexit.register(write_counter)
folders = ["to_post/", "not_posted/", "posted"]
for folder in folders:
if not path.exists(folder):
os.mkdir(folder)
print(os.getcwd())
# GUI
window = tk.Tk()
window.title("Confessions Bot")
window.geometry("600x350")
window.grid_columnconfigure((0,2), weight = 1)
label_tell_account = tk.Label(window, text = "Tellonym Account")
label_tell_password = tk.Label(window, text = "Tellonym Password")
label_ig_account = tk.Label(window, text = "Instagram Account")
label_ig_password = tk.Label(window, text = "Instagram Password")
tell_account = tk.Entry(window)
tell_password = tk.Entry(window)
ig_account = tk.Entry(window)
ig_password = tk.Entry(window)
image = ImageTk.PhotoImage(Image.open("logo.png"))
tk.Label(window, image = image).grid(row = 0, column = 1, padx = 10, pady = 10)
label_tell_account.grid(row = 1, column = 0)
tell_account.grid(row = 1, column = 2, padx = 10, pady = 10)
label_tell_password.grid(row = 2, column = 0, padx = 10, pady = 10)
tell_password.grid(row = 2, column = 2, padx = 10, pady = 10)
label_ig_account.grid(row = 3, column = 0, padx = 10, pady = 10)
ig_account.grid(row = 3, column = 2, padx = 10, pady = 10)
label_ig_password.grid(row = 4, column = 0, padx = 10, pady = 10)
ig_password.grid(row = 4, column = 2, padx = 10, pady = 10)
# run.grid(row = 5, column = 1, padx = 10, pady = 10)
window.mainloop()
When this is ran I get _tkinter.TclError: image "pyimage1" doesn't exist. I read that this happens since I haven't destroyed my initial window. If I change destroy_get() to have info.destroy() I'm no longer able to get the the entry from window A.
This is my first time using Tkinter and coding in general so any help is welcome.
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()```
In this file, I tried to return the value of employNum and employPass to the main function each time I clicked the display button. How can I do that?
from tkinter import *
def displayButton(root,employNum, employPass):
Label(root,text = employNum.get() ).grid(row = 3, column = 1, sticky = N+S+W+E)
Label(root, text = employPass.get()).grid(row = 4, column = 1, sticky = N+S+W+E)
def main():
root = Tk()
Label(root, text = 'Employee Number: ').grid(row = 0, column = 0, sticky = W)
Label(root, text = 'Login Password: ').grid(row = 1, column = 0, sticky = W)
employeeNum = StringVar()
employeePass = StringVar()
Entry(root, textvariable = employeeNum).grid(row = 0, column = 1, columnspan = 2, sticky = W)
Entry(root, textvariable = employeePass).grid(row = 1, column = 1, columnspan = 2, sticky = W)
checkButton = BooleanVar()
Checkbutton(root, text = 'Remember Me', variable = checkButton).grid(row = 2, column = 1, sticky = W)
Button(root, text = 'Save', relief = RAISED).grid(row = 2, column = 2, sticky = E)
display = Button(root, text = 'Display', relief = RAISED, command = lambda: displayButton(root, employeeNum,employeePass))
display.grid(row = 3, column = 2, sticky = E)
Label(root, text = "Employee's number is ").grid(row = 3, column = 0, sticky = W)
Label(root, text = "Employee's Passowrd is ").grid(row =4 , column = 0, sticky = W)
root.mainloop()
main()
Button can't return value using return. You can only set value in global variable or passed as argument. You can change text in Label assigned to global variable or passed as argument. You can create new Label but root have to be global variable or passed as argument.