How to really destroy a Frame so it disappears - python-3.x

I have a little program that does a search in a database and shows the results. My plan is to have the results show up in a suitably-sized frame in the same window where the search parameters were placed.
Since I want to replace the results for each new query, I have a results_owner frame which is permanent and has a single child results_frame which is populated and destroyed as required. At least, that's the plan. It is not going well.
I can create the frame and put stuff in it. But when I want to remove or replace it, I'm left with stuff from the previous incarnation. Some stuff is modified, some stuff seems permanent, and it baffles me.
You may have to make the window taller to see the full effect. The basic flaw is that when you click the "Line+" button, lines that show up are permanent, so that when you click the "new frame" button, lines should disappear but don't.
Here's code:
#!/usr/bin/env python3
"""Find a matching record in the database
Last Modified: Fri Dec 15 18:20:32 PST 2017
"""
import tkinter as tk # https://docs.python.org/3.5/library/tkinter.html
class Asker(tk.Frame):
def __init__(self, root=None):
super().__init__(root)
self.root = root
root.title("Asker")
self.pack()
self._create_widgets()
results_owner = None
results_frame = None
iteration = 0
def _create_widgets(self):
noterow2 = tk.Frame(root)
msgtx = "This represents the fixed area of the window"
tx2 = tk.Label(noterow2, width=len(msgtx), text=msgtx, anchor='w')
noterow2.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
tx2.pack(side=tk.LEFT, padx=5, pady=5)
buttonrow = tk.Frame(root)
buttonrow.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
b2 = tk.Button(buttonrow, text='Quit', command=root.quit)
b2.pack(side=tk.LEFT, padx=5, pady=5)
test1 = tk.Button(buttonrow, text='Line+', command=(lambda arg=self.results_frame: self.addline(arg)))
test1.pack(side=tk.LEFT, padx=5, pady=5)
test2 = tk.Button(buttonrow, text='New Frame', command=self.new_results)
test2.pack(side=tk.LEFT, padx=5, pady=5)
self.results_owner = tk.Frame(root)
self.results_owner.pack(side=tk.TOP, fill=tk.X)
self.new_results()
def new_results(self):
if self.results_frame is not None:
self.results_frame.destroy()
self.results_frame = tk.Frame(self.results_owner)
sampletxt = "New frame " + str(self.iteration)
sample = tk.Label(self.results_frame, text=sampletxt, width=len(sampletxt), anchor='w')
sample.pack(side=tk.LEFT, padx=5, pady=5)
self.results_frame.pack(side=tk.TOP,fill=tk.X,padx=0, pady=self.iteration)
self.root.update_idletasks()
self.iteration += 1
def addline(self, results):
print("addline")
msg = "New Line"
mytx = tk.Label(results, text=msg, width=len(msg), anchor='w')
mytx.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
if __name__ == '__main__':
root = tk.Tk()
anti = Asker(root=root)
anti.mainloop()
Here's modified code using some of the suggestions in comments (but it still does not work as intended):
#!/usr/bin/env python3
"""Find a matching record in the database
Last Modified: Fri Dec 15 20:31:17 PST 2017
"""
import tkinter as tk # https://docs.python.org/3.5/library/tkinter.html
class Asker(tk.Frame):
def __init__(self, root=None):
super().__init__(root)
self.root = root
root.title("Asker")
self.pack()
self.results_owner = None
self.results_frame = None
self.iteration = 0
self._create_widgets()
def _create_widgets(self):
noterow2 = tk.Frame(root)
msgtx = "This represents the fixed area of the window"
tx2 = tk.Label(noterow2, width=len(msgtx), text=msgtx, anchor='w')
noterow2.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
tx2.pack(side=tk.LEFT, padx=5, pady=5)
buttonrow = tk.Frame(root)
buttonrow.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
b2 = tk.Button(buttonrow, text='Quit', command=root.quit)
b2.pack(side=tk.LEFT, padx=5, pady=5)
test1 = tk.Button(buttonrow, text='Line+', command=self.addline(self.results_frame))
test1.pack(side=tk.LEFT, padx=5, pady=5)
test2 = tk.Button(buttonrow, text='New Frame', command=self.new_results)
test2.pack(side=tk.LEFT, padx=5, pady=5)
self.results_owner = tk.Frame(root)
self.results_owner.pack(side=tk.TOP, fill=tk.X)
self.new_results()
def new_results(self):
if self.results_frame is not None:
self.results_frame.pack_forget()
self.results_frame.destroy()
self.results_frame = tk.Frame(self.results_owner)
sampletxt = "New frame " + str(self.iteration)
sample = tk.Label(self.results_frame, text=sampletxt, width=len(sampletxt), anchor='w')
sample.pack(side=tk.LEFT, padx=5, pady=5)
self.results_frame.pack(side=tk.TOP,fill=tk.X,padx=0, pady=self.iteration)
self.root.update_idletasks()
self.iteration += 1
def addline(self, results):
print("addline")
msg = "New Line" + str(self.iteration)
mytx = tk.Label(results, text=msg, width=len(msg), anchor='w')
mytx.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
if __name__ == '__main__':
root = tk.Tk()
anti = Asker(root=root)
anti.mainloop()

In you situation you have to use self.results_frame directly in lambda
command=lambda:self.addline(self.results_frame)
to have access always to current value in variable self.results_frame
Using arg=self.results_frame in lambda
lambda arg=self.results_frame: self.addline(arg)
you copy value from self.results_frame to arg only once (at start) and later function uses the same value all the time.

It turns out I had to make the call to addline a lambda; as it was, the function was being called just once. I also adjusted packing and borders to make it clear how things are grouped. I can now use this as a model for my app.
#!/usr/bin/env python3
"""Last Modified: Sat Dec 16 07:28:31 PST 2017
"""
import tkinter as tk # https://docs.python.org/3.5/library/tkinter.html
class Asker(tk.Frame):
def __init__(self, root=None):
super().__init__(root)
self.root = root
root.title("Asker")
self.pack()
self.results_owner = None
self.results_frame = None
self.iteration = 0
self._create_widgets()
def _create_widgets(self):
noterow2 = tk.Frame(root)
msgtx = "This represents the fixed area of the window"
tx2 = tk.Label(noterow2, width=len(msgtx), text=msgtx, anchor='w')
noterow2.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
tx2.pack(side=tk.LEFT, padx=5, pady=5)
buttonrow = tk.Frame(root)
buttonrow.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
b2 = tk.Button(buttonrow, text='Quit', command=root.quit)
b2.pack(side=tk.LEFT, padx=5, pady=5)
test1 = tk.Button(buttonrow, text='Line+', command=(lambda :self.addline(self.results_frame)))
test1.pack(side=tk.LEFT, padx=5, pady=5)
test2 = tk.Button(buttonrow, text='New Frame', command=self.new_results)
test2.pack(side=tk.LEFT, padx=5, pady=5)
self.results_owner = tk.Frame(root, borderwidth=3, relief=tk.RAISED)
self.results_owner.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
self.new_results()
def new_results(self):
if self.results_frame is not None:
self.results_frame.destroy()
self.results_frame = tk.Frame(self.results_owner, borderwidth=1, relief=tk.GROOVE)
sampletxt = "New frame " + str(self.iteration)
sample = tk.Label(self.results_frame, text=sampletxt, width=len(sampletxt), anchor='w')
sample.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
self.results_frame.pack(side=tk.TOP,fill=tk.X,padx=2, pady=2)
self.root.update_idletasks()
self.iteration += 1
def addline(self, results):
msg = "New Line" + str(self.iteration)
mytx = tk.Label(results, text=msg, width=len(msg), anchor='w')
mytx.pack(side=tk.TOP, fill=tk.X, padx=2, pady=2)
self.root.update_idletasks()
self.iteration += 1
if __name__ == '__main__':
root = tk.Tk()
anti = Asker(root=root)
anti.mainloop()

Related

Python/tkinter - change entry status via checkbox

I want to activate the second entry when the checkbox is checked...but the it works the other way around. What am I doing wrong? Based on another question I have posted it seems the event "<ButtonRelease>" occurs before the bonding. Why is that? Can I use "command" in the checkbox instaed?
import tkinter as tk
def set_entry_status(event, var, widg):
print(var.get())
if var.get():
widg[-1]['state'] = 'normal'
else:
widg[-1]['state'] = 'disabled'
def CustomWidget(frame, name, unit, ):
var_e = []
widget_e = []
var_c = tk.IntVar(master=frame, value=0)
widget_c = tk.Checkbutton(master=frame, text='', variable=var_c)
widget_c.grid(row=0, column=0, columnspan=1, padx=5, pady=5, sticky="ns")
label_l = name + " (" + unit + ")" # nome + unità di misura in parentesi per GUI
widget_l = tk.Label(frame, text=label_l, padx=1, pady=1)
widget_l.grid(row=0, column=1, columnspan=1, padx=5, pady=5, sticky="wns")
var_e.append(tk.StringVar(master=frame, value='A'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=2, columnspan=1, padx=5, pady=5, sticky="ns")
var_e.append(tk.StringVar(master=frame, value='B'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=3, columnspan=1, padx=5, pady=5, sticky="ns")
# set initial entry state
if var_c.get():
widget_e[-1]['state'] = 'normal'
else:
widget_e[-1]['state'] = 'disabled'
# checkbox - binding
widget_c.bind("<ButtonRelease>", lambda event: set_entry_status(event, var_c, widget_e))
root = tk.Tk()
root.title('My Window')
CustomWidget(root, 'name', 'unit')
root.mainloop()
Indeed you can use command kwarg like I suggested in my other answer. In that case event must be removed from the arguments of your callback function:
import tkinter as tk
def set_entry_status(var, widg):
print(var.get())
if var.get():
widg[-1]['state'] = 'normal'
else:
widg[-1]['state'] = 'disabled'
def CustomWidget(frame, name, unit, ):
var_e = []
widget_e = []
var_c = tk.IntVar(master=frame, value=0)
widget_c = tk.Checkbutton(master=frame, text='', variable=var_c, command=lambda: set_entry_status(var_c, widget_e))
widget_c.grid(row=0, column=0, columnspan=1, padx=5, pady=5, sticky="ns")
label_l = name + " (" + unit + ")" # nome + unità di misura in parentesi per GUI
widget_l = tk.Label(frame, text=label_l, padx=1, pady=1)
widget_l.grid(row=0, column=1, columnspan=1, padx=5, pady=5, sticky="wns")
var_e.append(tk.StringVar(master=frame, value='A'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=2, columnspan=1, padx=5, pady=5, sticky="ns")
var_e.append(tk.StringVar(master=frame, value='B'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=3, columnspan=1, padx=5, pady=5, sticky="ns")
# set initial entry state
if var_c.get():
widget_e[-1]['state'] = 'normal'
else:
widget_e[-1]['state'] = 'disabled'
root = tk.Tk()
root.title('My Window')
CustomWidget(root, 'name', 'unit')
root.mainloop()

Is it possible to grab input from the topview tkinter window and retrieve saved entry field value from within master tk window

The program is made up of classes and I am trying to use a tkinter topview from within a function so that when it's called it is able to retrieve the entryfield value to the master class
from tkinter import
from PIL import Image, ImageTk
Below is the driver code handling the transitioning from one class to another
class SeaofBTCapp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (
WelcomePage, Register_new_user): # ,PageThree,PageFour):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(WelcomePage)
# def show_frame(self, cont):
# frame = self.frames[cont]
# frame.tkraise()
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
frame.update()
frame.event_generate("<<show_frame>>")
def get_page(self, cont):
for page in self.frames.values():
if str(page.__class__.__name__) == cont:
return page
return None
class Register_new_user(object):
pass
Below is the entry point of the program and is the first page to be displayed
class WelcomePage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
# self.bind("<<show_frame>>", self.main_prog)
def resize_image(event):
global photo
new_width = event.width
new_height = event.height
image = copy_of_image.resize((new_width, new_height))
photo = ImageTk.PhotoImage(image)
label.config(image=photo)
label.image = photo # avoid garbage collection
def pin_input():
top = Toplevel()
top.geometry("180x100")
top.title("toplevel")
l2 = Label(top, text="This is toplevel window")
global entry_1
global password
password = StringVar
entry_1 = None
def cleartxtfield():
global password
new = "3"
password.set(new)
# ############# Function to parse for only numerical input
def validate(input):
if input.isdigit():
return True
elif input == "":
return True
else:
return False
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
entry_1 = Entry(top, textvariable=password, width=64, show='*')
entry_1.place(x=200, y=100)
entry_1.focus()
reg = top.register(validate)
entry_1.config(validate="key", validatecommand=(reg, '%P'))
def getcreds():
# check if four digit entered and is not empty
global passwd
passwd = password.get()
print(f"The Credentials are {passwd}")
def funcbackspace():
length = len(entry_1.get())
entry_1.delete(length - 1, 'end')
def killwindow():
# when the user quits it should clear all the data input fields filled in in the previous steps. and should display information that it is about to quit in a few seconds
command = top.destroy()
# Label(top,text="Goodbye\n (Closing in 2 seconds)")
top.after(2000, top.quit())
cancel = Button(top, width=8, height=3, text="Cancel", bg="red", fg="black", command=killwindow)
cancel.place(x=220, y=150)
backspace = Button(top, width=8, height=3, text="Backspace", bg="red", fg="black", command=funcbackspace)
backspace.place(x=500, y=150)
# ----number Buttons------
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
btn_numbers = []
for i in range(10):
btn_numbers.append(
Button(top, width=8, height=3, text=str(i), bd=6, command=lambda x=i: enternumber(x)))
btn_text = 1
for i in range(0, 3):
for j in range(0, 3):
btn_numbers[btn_text].place(x=220 + j * 140, y=250 + i * 100)
btn_text += 1
btn_zero = Button(top, width=15, height=2, text='0', bd=5, command=lambda x=0: enternumber(x))
btn_zero.place(x=330, y=550)
clear = Button(top, text="Clear", bg="green", fg="white", width=8, height=3, command=cleartxtfield)
clear.place(x=220, y=550)
okbtn = Button(top, text="Enter", bg="green", fg="black", width=8, height=3, command=getcreds)
okbtn.place(x=500, y=550)
val = getcreds()
print("The value to be returned is %s" % val)
return val
password = pin_input()
print("Gotten password is %s" % password)
copy_of_image = Image.open("image.png")
photoimage = ImageTk.PhotoImage(copy_of_image)
label = Label(self, image=photoimage)
label.place(x=0, y=0, relwidth=1, relheight=1)
label.bind('<Configure>', resize_image)
top_left_frame = Frame(self, relief='groove', borderwidth=2)
top_left_frame.place(relx=1, rely=0.1, anchor=NE)
center_frame = Frame(self, relief='raised', borderwidth=2)
center_frame.place(relx=0.5, rely=0.75, anchor=CENTER)
Button(top_left_frame, text='REGISTER', bg='grey', width=14, height=1,
command=lambda: controller.show_frame(Register_new_user)).pack()
Button(center_frame, text='ENTER', fg='white', bg='green', width=13, height=2,
command=lambda: controller.show_frame(Register_new_user)).pack()
if __name__ == '__main__':
app = SeaofBTCapp()
app.title("Password return on topview window")
width = 1000
height = 700
screenwidth = app.winfo_screenwidth()
screenheight = app.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
app.geometry(alignstr)
# app.resizable(width=False, height=False)
app.resizable(width=True, height=True)
app.mainloop()
If I understand this correctly you want to enter a password in a dialog and then get the password from the dialog when you close it.
Have a look at Dialog Windows at effbot for a discussion about creating dialog windows.
Here is an example of how you can implement a simple dialog:
from tkinter import *
from tkinter import simpledialog
class MyDialog(simpledialog.Dialog):
def body(self, master):
'''create dialog body.
return widget that should have initial focus.
This method should be overridden, and is called
by the __init__ method.'''
Label(master, text='Value:').grid(row=0)
self.e1 = Entry(master)
self.e1.grid(row=0, column=1)
return self.e1 # initial focus
def apply(self):
'''process the data
This method is called automatically to process the data, *after*
the dialog is destroyed. By default, it does nothing.'''
value = self.e1.get()
self.result = value
def validate(self):
'''validate the data
This method is called automatically to validate the data before the
dialog is destroyed. By default, it always validates OK.'''
return 1 # override
def buttonbox(self):
'''add standard button box.
override if you do not want the standard buttons
'''
box = Frame(self)
w = Button(box, text="OK", width=10, command=self.ok, default='active')
w.pack(side='left', padx=5, pady=5)
w = Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side='left', padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
if __name__ == '__main__':
root = Tk()
root.geometry('200x100+800+50')
def do():
d = MyDialog(root)
print(d.result)
b = Button(root, text='Go!', width=10, command=do)
b.pack(expand=True)
Did that answer your question?

Multiprocessing not working with progress bar in tkinter

I'm attempting to get the progress bar to run while a method is running. The problem is when I set the method "generatePi" into the class it won't run simultaneously; however, when I set the method "generatePi" outside of the class it works.
The code with method in class that I can get to work is:
from tkinter import (Tk, BOTH, Text, E, W, S, N, END,
NORMAL, DISABLED, StringVar)
from tkinter.ttk import Frame, Label, Button, Progressbar, Entry
from tkinter import scrolledtext
from multiprocessing import Process, Manager, Queue
from queue import Empty
from decimal import Decimal, getcontext
DELAY1 = 80
DELAY2 = 20
q = Queue()
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, name="frame")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Pi computation")
self.pack(fill=BOTH, expand=True)
self.grid_columnconfigure(4, weight=1)
self.grid_rowconfigure(3, weight=1)
lbl1 = Label(self, text="Digits:")
lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10)
self.ent1 = Entry(self, width=10)
self.ent1.insert(END, "4000")
self.ent1.grid(row=0, column=1, sticky=W)
lbl2 = Label(self, text="Accuracy:")
lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10)
self.ent2 = Entry(self, width=10)
self.ent2.insert(END, "100")
self.ent2.grid(row=0, column=3, sticky=W)
self.startBtn = Button(self, text="Start",
command=self.onStart)
self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W)
self.pbar = Progressbar(self, mode='indeterminate')
self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E)
self.txt = scrolledtext.ScrolledText(self)
self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5,
columnspan=5, sticky=E+W+S+N)
def onStart(self):
self.startBtn.config(state=DISABLED)
self.txt.delete("1.0", END)
digits = int(self.ent1.get())
accuracy = int(self.ent2.get())
self.p1 = Process(target=generatePi(q, digits, accuracy), args=())
self.p1.start()
self.pbar.start(DELAY2)
self.after(DELAY1, self.onGetValue)
def onGetValue(self):
if (self.p1.is_alive()):
self.after(DELAY1, self.onGetValue)
return
else:
try:
self.txt.insert('end', q.get(0))
self.txt.insert('end', "\n")
self.pbar.stop()
self.startBtn.config(state=NORMAL)
except Empty:
print("queue is empty")
def generatePi(q, digs, acc):
getcontext().prec = digs
pi = Decimal(0)
k = 0
n = acc
while k < n:
pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1)) - \
(Decimal(2)/(8*k+4)) - (Decimal(1)/(8*k+5))- \
(Decimal(1)/(8*k+6)))
k += 1
q.put(pi)
def main():
root = Tk()
root.geometry("400x350+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
The code with method outside class that I am unable to get to work:
from tkinter import (Tk, BOTH, Text, E, W, S, N, END,
NORMAL, DISABLED, StringVar)
from tkinter.ttk import Frame, Label, Button, Progressbar, Entry
from tkinter import scrolledtext
from multiprocessing import Process, Manager, Queue
from queue import Empty
from decimal import Decimal, getcontext
DELAY1 = 80
DELAY2 = 20
q = Queue()
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, name="frame")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Pi computation")
self.pack(fill=BOTH, expand=True)
self.grid_columnconfigure(4, weight=1)
self.grid_rowconfigure(3, weight=1)
lbl1 = Label(self, text="Digits:")
lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10)
self.ent1 = Entry(self, width=10)
self.ent1.insert(END, "4000")
self.ent1.grid(row=0, column=1, sticky=W)
lbl2 = Label(self, text="Accuracy:")
lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10)
self.ent2 = Entry(self, width=10)
self.ent2.insert(END, "100")
self.ent2.grid(row=0, column=3, sticky=W)
self.startBtn = Button(self, text="Start",
command=self.onStart)
self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W)
self.pbar = Progressbar(self, mode='indeterminate')
self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E)
self.txt = scrolledtext.ScrolledText(self)
self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5,
columnspan=5, sticky=E+W+S+N)
def onStart(self):
self.startBtn.config(state=DISABLED)
self.txt.delete("1.0", END)
digits = int(self.ent1.get())
accuracy = int(self.ent2.get())
self.p1 = Process(target=self.generatePi(q, digits, accuracy), args=())
self.p1.start()
self.pbar.start(DELAY2)
self.after(DELAY1, self.onGetValue)
def onGetValue(self):
if (self.p1.is_alive()):
self.after(DELAY1, self.onGetValue)
return
else:
try:
self.txt.insert('end', q.get(0))
self.txt.insert('end', "\n")
self.pbar.stop()
self.startBtn.config(state=NORMAL)
except Empty:
print("queue is empty")
def generatePi(self, q, digs, acc):
getcontext().prec = digs
pi = Decimal(0)
k = 0
n = acc
while k < n:
pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1)) - \
(Decimal(2)/(8*k+4)) - (Decimal(1)/(8*k+5))- \
(Decimal(1)/(8*k+6)))
k += 1
q.put(pi)
def main():
root = Tk()
root.geometry("400x350+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
With the change in code being:
self.p1 = Process(target=generatePi(q, digits, accuracy), args=())
To:
self.p1 = Process(target=self.generatePi(q, digits, accuracy), args=())
I got same problem when I try it I find windows system seems react late but in terminal it's actually running

Change Entry widget value from other function

I am quite new in programming with tkinter , especially with classes. How can I make a button that runs function from the same class and changes entry widget. In my code i want to change entry1 whenever button1 is clicked and filepath function runs.
thank you for your help.
Class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def filepath():
filename = fd.askopenfilename()
entry1.delete(0,END)
entry1.insert(0,filename)
def initUI(self):
self.master.title("EFEKTYWNOŚĆ APP")
self.pack(fill=BOTH, expand=True)
cd = (os.getcwd())
frame1 = Frame(self)
frame1.pack(side = LEFT)
lbl1 = Label(frame1,
text="...",
wraplength = 250 )
lbl1.pack(side=LEFT, padx=5, pady=5)
path = os.path.join(cd, 'ico', '...')
photo = PhotoImage(file = path)
cphoto = photo.subsample(4,4)
button1 = Button(frame1,
text='WYBIERZ PLIK',
image = cphoto,
compound = LEFT,
command = Example.filepath)
button1.image = cphoto
button1.pack(side=LEFT, fill = Y, padx=5, pady=5)
entry1 = Entry(frame1)
entry1.pack(side=LEFT, fill = Y, padx=5, pady=5)
There are some minor things needed to be fixed in your code. I have added a working sample with comments below.
from tkinter import *
from tkinter import filedialog as fd
import os
class Example(Frame):
def __init__(self, master,**kwargs): #have your Frame accept parameters like how a normal frame should
super().__init__(master,**kwargs)
self.master = master #set master as an attribute so you can access it later
self.initUI()
def filepath(self): #add self to make the method an instance method
filename = fd.askopenfilename()
self.entry1.delete(0, END) #use self when referring to an instance attribute
self.entry1.insert(0, filename)
def initUI(self):
self.master.title("EFEKTYWNOŚĆ APP")
self.pack(fill=BOTH, expand=True)
cd = (os.getcwd())
frame1 = Frame(self)
frame1.pack(side=LEFT)
lbl1 = Label(frame1,
text="...",
wraplength=250)
lbl1.pack(side=LEFT, padx=5, pady=5)
path = os.path.join(cd, 'ico', '...')
photo = PhotoImage(file=path)
cphoto = photo.subsample(4, 4)
button1 = Button(frame1,
text='WYBIERZ PLIK',
image=cphoto,
compound=LEFT,
command=self.filepath) #refer to instance methods by self.your_method
button1.pack(side=LEFT, fill=Y, padx=5, pady=5)
self.entry1 = Entry(frame1) #add self to make it an instance attribute
self.entry1.pack(side=LEFT, fill=Y, padx=5, pady=5) #you will then need to use self.entry1 within your class instance
root = Tk()
Example(root)
root.mainloop()

My program doesn't work when i compile it?

i made a tkinter program. the program is working well when i run it. but when i compile it using cx_Freeze it work well when i use the command python setup.py build . but when i use the command python setup.py bdist_msi to build a simple installer.it doesn't work well and doesn't do his functionality
i am using python 3.6.2 64bit
this is my setup.py:
import cx_Freeze
import sys
import os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')
base = None
if sys.platform == 'win32':
base = "Win32GUI"
executables = [cx_Freeze.Executable("Tasks_Organiser.py", base=base, icon="iccon.ico")]
cx_Freeze.setup(
name = "Tasks Organiser",
options = {"build_exe": {"packages":["tkinter","sqlite3"], "include_files":["iccon.ico", "favicon.ico", "Notes.db", os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),
os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll')]}},
version = "0.01",
description = "GUI APP",
executables = executables
)
and this is my program:
from tkinter import *
from tkinter import ttk
from time import ctime
from tkinter import messagebox
import sqlite3
class Organise:
def __init__(self):
self.conn = sqlite3.connect("Notes.db")
self.conn.row_factory = sqlite3.Row
self.c = self.conn.cursor()
self.c.execute("CREATE TABLE IF NOT EXISTS organise (TaskName TEXT, timefrom TEXT, timeto TEXT, Comment TEXT, TaskType TEXT)")
self.conn.commit()
def add_to_db(self, taskname, From, To, Comment, task_type):
self.c.execute("INSERT INTO organise (TaskName, timefrom, timeto, Comment, TaskType) VALUES (?, ?, ?, ?, ?)", (taskname, From, To, Comment, task_type))
self.conn.commit()
def call_from_db(self):
call = self.c.execute("SELECT * FROM organise").fetchall()
return call
def select_tasks(self):
select = self.c.execute("SELECT TaskName FROM organise")
return select
def delete(self, task):
self.c.execute("DELETE FROM organise WHERE TaskName ='{}'".format(task))
self.conn.commit()
def select_row(self, task):
self.c.execute("SELECT TaskName, timefrom, timeto, Comment, TaskType FROM organise WHERE TaskName = '%s'"%task)
def add():
add = AddTask()
root = Tk()
root.title("OrganiseNotes")
root.iconbitmap("favicon.ico")
root.configure(background="#00b4f0")
style = ttk.Style()
style.configure("TLabel", background="#00b3ad")
style.configure("TButton", background="#173701", forebackground="black", relief="flat")
style.map("TButton",
foreground=[('pressed', '#4b63a1'), ('active', '#00b4f0')],
background=[('pressed', '!disabled', 'black'), ('active', '#2d74ae')])
style.configure("TRadiobutton", background="#e3e2dd")
style.configure("Treeview", background='#adaca7')
# the organise label with the date of that day(today)
today = ctime()[:10]+ctime()[19:]
start_label = ttk.Label(root, text="Organise {}".format(today), font=("Helvetica", 18, "bold"), compound="center")
start_label.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
# the Add task Button
add_bu = ttk.Button(root, text="Add Task")
add_bu.grid(row=1, column=2, padx=10)
add_bu.config(command=add)
# the delete button
dele_bu = ttk.Button(root, text="Delete")
dele_bu.grid(row=2, column=2, padx=10)
# end the day Button (Production of your day)
endday_bu = ttk.Button(root, text="End The Day")
endday_bu.grid(row=3, column=2, padx=10)
class TvShow:
def __init__(self):
self.organ = Organise()
self.tv = ttk.Treeview(root)
self.tv.grid(row=1, column=0, columnspan=2, rowspan=3, padx=10, pady=30)
self.tv.heading("#0", text="ID")
self.tv.configure(column=("#TaskName", "#From", "#To", "#Comment", "#TaskType"))
self.tv.heading("#TaskName", text="TaskName")
self.tv.heading("#From", text="From")
self.tv.heading("#To", text="To")
self.tv.heading("#Comment", text="Comment")
self.tv.heading("#TaskType", text="TaskType")
self.tv.column("#0", width=50)
self.tv.column("#TaskName", width=200, anchor="center")
self.tv.column("#From", width=100, anchor="center")
self.tv.column("#To", width=100, anchor="center")
self.tv.column("#Comment", width=300, anchor="center")
self.i = 1
self.s = self.organ.call_from_db()
def add_to_tv(self, taskname, tfrom, tto, comment, task_type):
self.tv.insert("", "end", text=str(self.i), values=(taskname, tfrom, tto, comment, task_type))
self.i += 1
def del_from_tv(self):
choose = self.tv.selection()
if len(choose) != 0:
choose2 = choose[0]
item_name = self.tv.item(choose2)["values"][0]
self.organ.delete(item_name)
self.tv.delete(choose)
return messagebox.showinfo(title="Task deleted", message="The Task is deleted")
else:
return messagebox.showerror(title="Error", message="Select the task you want to delete")
class AddTask:
def __init__(self):
self._root = Toplevel()
self._root.configure(background="#00b4f0")
self._root.iconbitmap("favicon.ico")
# the task name section
ttk.Label(self._root, text="Task Name").grid(row=0, column=0, padx=10, pady=10)
self.taskname_enter = ttk.Entry(self._root)
self.taskname_enter.grid(row=0, column=1)
# the from (time) section
ttk.Label(self._root, text="From : ").grid(row=1, column=0, padx=10, pady=10)
ttk.Label(self._root, text="hour").grid(row=1, column=1)
self.From_enter_hour = ttk.Entry(self._root, width=5)
self.From_enter_hour.grid(row=1, column=2, padx=20)
ttk.Label(self._root, text=":").grid(row=1, column=3)
ttk.Label(self._root, text="minutes").grid(row=1, column=4)
self.From_enter_min = ttk.Entry(self._root, width=5)
self.From_enter_min.grid(row=1, column=5, padx=5, pady=5)
# the to (time) section
ttk.Label(self._root, text="To:").grid(row=2, column=0)
ttk.Label(self._root, text="hour").grid(row=2, column=1)
self.To_enter_hour = ttk.Entry(self._root, width=5)
self.To_enter_hour.grid(row=2, column=2)
ttk.Label(self._root, text=":").grid(row=2, column=3)
ttk.Label(self._root, text="minutes").grid(row=2, column=4)
self.To_enter_min = ttk.Entry(self._root, width=5)
self.To_enter_min.grid(row=2, column=5,padx=5, pady=5)
# the comment section
ttk.Label(self._root, text="Comment").grid(row=3, column=0, padx=10, pady=10)
self.comment_enter = Text(self._root, width=20, height=10)
self.comment_enter.grid(row=3, column=1)
# the task type section
ttk.Label(self._root, text="Task Type").grid(row=4, column=0, padx=10, pady=10)
self.value_type = StringVar()
self.R1 = ttk.Radiobutton(self._root, text="Very Important", variable=self.value_type, value="Very Important")
self.R1.grid(row=4, column=1, padx=10, pady=10)
self.R2 = ttk.Radiobutton(self._root, text=" Important", variable=self.value_type, value="Important")
self.R2.grid(row=5, column=1, padx=10, pady=10)
self.R3 = ttk.Radiobutton(self._root, text=" Not Important", variable=self.value_type, value="Not Important")
self.R3.grid(row=6, column=1)
# the save button section
self.save_bu = ttk.Button(self._root, text="Save")
self.save_bu.grid(row=7, column=4, padx=10, pady=10)
self.save_bu.config(command=self.busave)
self._root.mainloop()
def busave(self):
try:
check_from_hour = int(self.From_enter_hour.get())
check_from_min = int(self.From_enter_min.get())
check_to_hour = int(self.To_enter_hour.get())
check_to_min = int(self.To_enter_min.get())
From_enter= str(check_from_hour)+":"+str(check_from_min)
To_enter = str(check_to_hour) + ":" + str(check_to_min)
self.organ = Organise()
self.organ.add_to_db(self.taskname_enter.get(), From_enter, To_enter, self.comment_enter.get(1.0, "end"), self.value_type.get())
self.s = self.organ.call_from_db()
row = self.s[-1]
tv.add_to_tv(row[0], row[1], row[2], row[3], row[4])
self.taskname_enter.delete(0, "end")
self.From_enter_hour.delete(0, "end")
self.From_enter_min.delete(0, "end")
self.To_enter_hour.delete(0, "end")
self.To_enter_min.delete(0, "end")
self.comment_enter.delete(1.0, "end")
self.value_type.set("")
except:
messagebox.showinfo(title="invalid inputs", message="From and To inputs should be numbers(ex: 3:56)")
class ProductionDay:
def __init__(self):
self.organ = Organise()
self.tasks = self.organ.select_tasks()
self.tasks_list = []
for i in self.tasks:
self.tasks_list.append(i[0])
self.check = [IntVar(value=0) for i in range(len(self.tasks_list))]
if len(self.tasks_list) != 0:
self.root = Toplevel()
self.root.configure(background="#00b4f0")
self.root.iconbitmap("favicon.ico")
self.root.iconbitmap("favicon.ico")
self.root.title("Your Productivity of Today")
for x in range(len(self.tasks_list)):
ttk.Label(self.root, text=self.tasks_list[x]).grid(row=x, column=0, padx = 10, pady=10)
chech_button = ttk.Checkbutton(self.root, text="done", variable=self.check[x], onvalue=1, offvalue=0).grid(row=x, column=2, padx=10, pady=10)
save_button = ttk.Button(self.root, text="My Productivity")
save_button.grid(row=len(self.tasks_list), column=1, padx=150, pady=10)
save_button.config(command=lambda:self.precentage(self.check))
self.root.mainloop()
else:
messagebox.showerror(title="Error", message="There are no tasks to show")
def precentage(self, checks):
checked_ones = [i.get() for i in checks]
one_count = checked_ones.count(1)
percentage = (one_count/len(checked_ones))*100
messagebox.showinfo(title="Productivity of %s"%today, message="Your Productivity is %s" %str(percentage))
self.root.quit()
def product():
pro = ProductionDay()
endday_bu.config(command= lambda:product())
tv = TvShow()
dele_bu.config(command=lambda:tv.del_from_tv())
for row in tv.s:
tv.add_to_tv(row[0], row[1], row[2], row[3], row[4])
root.mainloop()
Create a folder in your drive C and name it LOCAL_TO_PYTHON, then create another folder inside it and named it PYTHON35-32.Go to the folder or directory where you have your python installed and search the folder named tcl and copy and paste it PYTHON35-32.
Go to your python directory and search for DLL folder inside the folder copy tcl and tk86 and paste it in the tcl folder your copied to the folder you created.
Then convert the program again the issue will be solved . Pay attention to how i named the folders i created.
see this link to resolve it

Resources