I am new to Tkinter/OOP and would like some help, I am currently stuck making a gui for a application. The functionality i want is that when a new window using the TopLevel() widget is spawned the button used for it to become disabled, which i have achieved. However the problem is enabling it after the spawned window is closed.
And in general how does one go about modifying the main tkinter root window from a TopLevel() widget using an OOP based approach. As i would like to do more stuff later on
The code is as follows:
from tkinter import *
from tkinter import ttk
class MainWindow:
def __init__(self, top):
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#d9d9d9' # X11 color: 'gray85'
font10 = "-family {Segoe UI} -size 10 -weight normal -slant " \
"roman -underline 0 -overstrike 0"
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.', background=_bgcolor)
self.style.configure('.', foreground=_fgcolor)
self.style.configure('.', font="TkDefaultFont")
self.style.map('.', background=
[('selected', _compcolor), ('active', _ana2color)])
self.top=top
self.top.geometry("214x96+462+349")
self.top.title("Test")
self.top.configure(background="#d9d9d9")
self.top.configure(highlightbackground="#d9d9d9")
self.top.configure(highlightcolor="black")
self.top.resizable(0, 0)
self.Btn_UI = Button(self.top)
self.Btn_UI.place(relx=0.50, rely=0.21, height=24, width=100)
self.Btn_UI.configure(activebackground="#d9d9d9")
self.Btn_UI.configure(activeforeground="#000000")
self.Btn_UI.configure(background="#d9d9d9")
self.Btn_UI.configure(command=self.Btn_UI_fun)
self.Btn_UI.configure(disabledforeground="#a3a3a3")
self.Btn_UI.configure(foreground="#000000")
self.Btn_UI.configure(highlightbackground="#d9d9d9")
self.Btn_UI.configure(highlightcolor="black")
self.Btn_UI.configure(pady="0")
self.Btn_UI.configure(text='''New Window''')
def Btn_UI_fun(self):
print('button')
root2 = Toplevel(self.top)
second = SettingsWindow(root2)
self.Btn_UI.configure(state="disabled")
return
class SettingsWindow():
def __init__(self, master):
self.master=master
self.master.geometry("214x96+462+349")
self.master.title("New")
self.master.configure(background="#d9d9d9")
self.master.configure(highlightbackground="#d9d9d9")
self.master.configure(highlightcolor="black")
self.master.resizable(0, 0)
self.Btn = Button(self.master)
self.Btn.place(relx=0.50, rely=0.21, height=24, width=51)
self.Btn.configure(text='''Quite''')
self.Btn.configure(command=self.quite)
def quite(self):
p = MainWindow.__init__
p.self.Btn_UI.configure(state="normal")
self.master.destroy()
def main():
root = Tk()
Main = MainWindow(root)
root.mainloop()
main()
Thanks in Advance!! :D
Related
main.py
import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
from PIL import ImageTk, Image
from tkinter import *
import main_support
def popup1(event, *args, **kwargs):
Popupmenu1 = tk.Menu(main_support.root, tearoff=0)
Popupmenu1.configure(activebackground="#ececec")
Popupmenu1.configure(activeborderwidth="1")
Popupmenu1.configure(activeforeground="#000000")
Popupmenu1.configure(background="#d9d9d9")
Popupmenu1.configure(borderwidth="1")
Popupmenu1.configure(disabledforeground="#a3a3a3")
Popupmenu1.configure(font="-family {Segoe UI} -size 9")
Popupmenu1.configure(foreground="#000000")
Popupmenu1.post(event.x_root, event.y_root)
class Header:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
self.methodSelectionValue = []
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+664+264")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("Toplevel 0")
top.configure(background="#d9d9d9")
top.configure(highlightbackground="#f0f0f0f0f0f0")
top.configure(highlightcolor="black")
self.top = top
self.combobox = tk.StringVar()
self.Label1 = tk.Label(self.top)
self.Label1.place(relx=-0.033, rely=0.0, height=41, width=634)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#b90746")
self.Label1.configure(compound='center')
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(font="-family {Calisto MT} -size 16 -weight bold -slant italic")
self.Label1.configure(foreground="#ffffff")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''Calculator''')
self.TFrame1 = ttk.Frame(self.top)
self.TFrame1.place(relx=0.02, rely=0.12, relheight=0.856, relwidth=0.958)
self.TFrame1.configure(relief='groove')
self.TFrame1.configure(borderwidth="2")
self.TFrame1.configure(relief="groove")
self.Labelframe1 = tk.LabelFrame(self.TFrame1)
self.Labelframe1.place(relx=0.47, rely=0.026, relheight=0.948, relwidth=0.504)
self.Labelframe1.configure(relief='groove')
self.Labelframe1.configure(foreground="black")
self.Labelframe1.configure(text='''Main Window''')
self.Labelframe1.configure(background="#d9d9d9")
self.Labelframe1.configure(highlightbackground="#d9d9d9")
self.Labelframe1.configure(highlightcolor="black")
self.Label2 = tk.Label(self.Labelframe1)
self.Label2.place(relx=0.038, rely=0.11, height=31, width=90, bordermode='ignore')
self.Label2.configure(activebackground="#f9f9f9")
self.Label2.configure(activeforeground="black")
self.Label2.configure(anchor='w')
self.Label2.configure(background="#d9d9d9")
self.Label2.configure(compound='left')
self.Label2.configure(disabledforeground="#a3a3a3")
self.Label2.configure(foreground="#000000")
self.Label2.configure(highlightbackground="#d9d9d9")
self.Label2.configure(highlightcolor="black")
self.Label2.configure(text='''Class Selection''')
self.TCombobox1 = ttk.Combobox(self.Labelframe1, values=['Basic', 'Advance'])
self.TCombobox1.bind("<<ComboboxSelected>>", self.setMethodValue)
self.TCombobox1.place(relx=0.421, rely=0.121, relheight=0.058, relwidth=0.531, bordermode='ignore')
self.TCombobox1.configure(textvariable=self.combobox)
self.TCombobox1.configure(takefocus="")
self.Label3 = tk.Label(self.Labelframe1)
self.Label3.place(relx=0.038, rely=0.274, height=21, width=111, bordermode='ignore')
self.Label3.configure(activebackground="#f9f9f9")
self.Label3.configure(activeforeground="black")
self.Label3.configure(anchor='w')
self.Label3.configure(background="#d9d9d9")
self.Label3.configure(compound='left')
self.Label3.configure(disabledforeground="#a3a3a3")
self.Label3.configure(foreground="#000000")
self.Label3.configure(highlightbackground="#d9d9d9")
self.Label3.configure(highlightcolor="black")
self.Label3.configure(text='''Method Selection''')
self.TCombobox2 = ttk.Combobox(self.Labelframe1, values=self.methodSelectionValue)
self.TCombobox2.place(relx=0.414, rely=0.274, relheight=0.058, relwidth=0.528, bordermode='ignore')
self.TCombobox2.configure(textvariable=self.combobox)
self.TCombobox2.configure(takefocus="")
self.TEntry1 = ttk.Entry(self.Labelframe1)
self.TEntry1.place(relx=0.138, rely=0.493, relheight=0.112, relwidth=0.262, bordermode='ignore')
self.TEntry1.configure(takefocus="")
self.TEntry1.configure(cursor="ibeam")
self.Label4 = tk.Label(self.Labelframe1)
self.Label4.place(relx=0.207, rely=0.411, height=21, width=74, bordermode='ignore')
self.Label4.configure(activebackground="#f9f9f9")
self.Label4.configure(activeforeground="black")
self.Label4.configure(anchor='w')
self.Label4.configure(background="#d9d9d9")
self.Label4.configure(compound='left')
self.Label4.configure(disabledforeground="#a3a3a3")
self.Label4.configure(foreground="#000000")
self.Label4.configure(highlightbackground="#d9d9d9")
self.Label4.configure(highlightcolor="black")
self.Label4.configure(text='''Input 1''')
self.TEntry2 = ttk.Entry(self.Labelframe1)
self.TEntry2.place(relx=0.621, rely=0.493, relheight=0.112, relwidth=0.262, bordermode='ignore')
self.TEntry2.configure(takefocus="")
self.TEntry2.configure(cursor="ibeam")
self.Label5 = tk.Label(self.Labelframe1)
self.Label5.place(relx=0.655, rely=0.411, height=21, width=44, bordermode='ignore')
self.Label5.configure(activebackground="#f9f9f9")
self.Label5.configure(activeforeground="black")
self.Label5.configure(anchor='w')
self.Label5.configure(background="#d9d9d9")
self.Label5.configure(compound='left')
self.Label5.configure(disabledforeground="#a3a3a3")
self.Label5.configure(foreground="#000000")
self.Label5.configure(highlightbackground="#d9d9d9")
self.Label5.configure(highlightcolor="black")
self.Label5.configure(text='''Input 2''')
self.Button1 = tk.Button(self.Labelframe1)
self.Button1.place(relx=0.397, rely=0.685, height=34, width=57, bordermode='ignore')
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(compound='left')
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Run''')
self.TFrame2 = ttk.Frame(self.TFrame1)
self.TFrame2.place(relx=0.017, rely=0.026, relheight=0.948, relwidth=0.426)
self.TFrame2.configure(relief='groove')
self.TFrame2.configure(borderwidth="2")
self.TFrame2.configure(relief="groove")
def setMethodValue(self, event):
selectedValue = self.TCombobox1.get()
if selectedValue == "Basic":
self.TCombobox2["values"] = ["Add", "Sub"]
elif selectedValue == "Advance":
self.TCombobox2["values"] = ["Multiply", "Division", "Modulus"]
self.TCombobox2.current()
def start_up():
main_support.mains()
if __name__ == '__main__':
main_support.mains()
main_support.py
import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
import main
def mains(*args):
'''Main entry point for the application.'''
global root
root = tk.Tk()
root.protocol( 'WM_DELETE_WINDOW' , root.destroy)
# Creates a toplevel widget.
global _top1, _w1
_top1 = root
_w1 = main.Header(_top1)
root.mainloop()
if __name__ == '__main__':
main.start_up()
Created two dropdowns one is for class selection and other is for method selection of that particular class. class name: basic, advance, method selection: basic: add,sub, advance:multiply, division and modulus. currently struck at issue where i select class as basic, it shows basic in method selection dropdown also which is not inteded. thereafter if i select class as basic and in method i select add, class which has to be basic is also getting changed to add. help me out.
You have used same tkinter variable self.combobox for both Combobox widgets.
Remove the line:
self.TCombobox2.configure(textvariable=self.combobox)
Or use another tkinter variable for self.TCombobox2.
Please can you help me I don't know what´s the problem.
This is the Error:
[Running] python -u "c:\Users\Leon\Desktop\Page Guis\Music Player Pro ++\unknown.py"
File "c:\Users\Leon\Desktop\Page Guis\Music Player Pro ++\unknown.py", line 49
mixer.music.play()
^
TabError: inconsistent use of tabs and spaces in indentation
[Done] exited with code=1 in 0.651 seconds
My code:
# -*- coding: utf-8 -*-
from pygame import mixer
import tkinter.filedialog
import sys
try:
import tkinter as tk
except ImportError:
import tkinter as tk
try:
import tkinter.ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import unknown_support
mixer.init()
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
unknown_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(rt, *args, **kwargs):
'''Starting point when module is imported by another module.
Correct form of call: 'create_Toplevel1(root, *args, **kwargs)' .'''
global w, w_win, root
#rt = root
root = rt
w = tk.Toplevel (root)
top = Toplevel1 (w)
unknown_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
def load_song():
mixer.music.load(tk.filedialog.askopenfile())
mixer.music.play()
def pause_song():
mixer.music.pause()
def resume():
mixer.music.unpause()
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
top.geometry("600x430+314+157")
top.minsize(120, 1)
top.maxsize(1370, 729)
top.resizable(1, 1)
top.title("Musik Player Pro ++")
top.configure(relief="groove")
top.configure(background="#000000")
top.configure(highlightbackground="#d9d9d9")
top.configure(highlightcolor="black")
self.menubar = tk.Menu(top,font="TkMenuFont",bg=_bgcolor,fg=_fgcolor)
top.configure(menu = self.menubar)
self.Canvas1 = tk.Canvas(top)
self.Canvas1.place(relx=0.867, rely=0.116, relheight=0.658
, relwidth=0.122)
self.Canvas1.configure(background="#000000")
self.Canvas1.configure(borderwidth="2")
self.Canvas1.configure(highlightbackground="#d9d9d9")
self.Canvas1.configure(highlightcolor="black")
self.Canvas1.configure(insertbackground="#4fff53")
self.Canvas1.configure(relief="ridge")
self.Canvas1.configure(selectbackground="#48ffff")
self.Canvas1.configure(selectforeground="white")
self.Label1 = tk.Label(top)
self.Label1.place(relx=0.667, rely=0.023, height=41, width=194)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#000000")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(font="-family {Tw Cen MT Condensed} -size 14 -weight bold -slant italic -underline 1")
self.Label1.configure(foreground="#ffffff")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''Volume''')
self.Scale1 = tk.Scale(top, from_=0.0, to=100.0)
self.Scale1.place(relx=0.767, rely=0.116, relwidth=0.0, relheight=0.665
, width=45, bordermode='ignore')
self.Scale1.configure(activebackground="#ececec")
self.Scale1.configure(background="#000000")
self.Scale1.configure(font="-family {Tw Cen MT Condensed} -size 14 -weight bold -underline 1")
self.Scale1.configure(foreground="#ffffff")
self.Scale1.configure(highlightbackground="#d9d9d9")
self.Scale1.configure(highlightcolor="black")
self.Scale1.configure(label="Volume")
self.Scale1.configure(relief="groove")
self.Scale1.configure(troughcolor="#d9d9d9")
self.tooltip_font = "TkDefaultFont"
self.Scale1_tooltip = \
ToolTip(self.Scale1, self.tooltip_font, '''Volume + / -''')
self.Label1_2 = tk.Label(top)
self.Label1_2.place(relx=0.017, rely=0.023, height=41, width=194)
self.Label1_2.configure(activebackground="#f9f9f9")
self.Label1_2.configure(activeforeground="black")
self.Label1_2.configure(anchor='w')
self.Label1_2.configure(background="#000000")
self.Label1_2.configure(compound='left')
self.Label1_2.configure(disabledforeground="#a3a3a3")
self.Label1_2.configure(font="-family {Tw Cen MT Condensed} -size 14 -weight bold -slant italic -underline 1")
self.Label1_2.configure(foreground="#ffffff")
self.Label1_2.configure(highlightbackground="#d9d9d9")
self.Label1_2.configure(highlightcolor="black")
self.Label1_2.configure(text='''Now playing:''')
self.Label2 = tk.Label(top)
self.Label2.place(relx=0.267, rely=0.279, height=101, width=164)
self.Label2.configure(activebackground="#f9f9f9")
self.Label2.configure(activeforeground="black")
self.Label2.configure(background="#000000")
self.Label2.configure(disabledforeground="#a3a3a3")
self.Label2.configure(font="-family {Segoe UI Black} -size 15 -weight bold -slant italic -underline 1")
self.Label2.configure(foreground="#ffffff")
self.Label2.configure(highlightbackground="#d9d9d9")
self.Label2.configure(highlightcolor="black")
self.Label2.configure(text='''Track Name''')
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.017, rely=0.837, height=64, width=187)
self.Button1.configure(activebackground="#ffffff")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#000000")
self.Button1.configure(cursor="fleur")
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#ffffff")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(relief="groove")
self.Button1.configure(text='''Resume''')
self.Button1.configure(command=resume)
self.Button1_1 = tk.Button(top)
self.Button1_1.place(relx=0.35, rely=0.837, height=64, width=187)
self.Button1_1.configure(activebackground="#ffffff")
self.Button1_1.configure(activeforeground="#000000")
self.Button1_1.configure(background="#000000")
self.Button1_1.configure(disabledforeground="#a3a3a3")
self.Button1_1.configure(foreground="#ffffff")
self.Button1_1.configure(highlightbackground="#d9d9d9")
self.Button1_1.configure(highlightcolor="black")
self.Button1_1.configure(pady="0")
self.Button1_1.configure(relief="groove")
self.Button1_1.configure(text='''Pause''')
self.Button1_1.configure(command=pause_song)
self.Button1_1_1 = tk.Button(top)
self.Button1_1_1.place(relx=0.683, rely=0.837, height=64, width=187)
self.Button1_1_1.configure(activebackground="#ffffff")
self.Button1_1_1.configure(activeforeground="#000000")
self.Button1_1_1.configure(background="#000000")
self.Button1_1_1.configure(disabledforeground="#a3a3a3")
self.Button1_1_1.configure(foreground="#ffffff")
self.Button1_1_1.configure(highlightbackground="#d9d9d9")
self.Button1_1_1.configure(highlightcolor="black")
self.Button1_1_1.configure(pady="0")
self.Button1_1_1.configure(relief="groove")
self.Button1_1_1.configure(text='''Load Song''')
self.Button1_1_1.configure(command=load_song)
from time import time, localtime, strftime
class ToolTip(tk.Toplevel):
"""
Provides a ToolTip widget for Tkinter.
To apply a ToolTip to any Tkinter widget, simply pass the widget to the
ToolTip constructor
"""
def __init__(self, wdgt, tooltip_font, msg=None, msgFunc=None,
delay=0.5, follow=True):
"""
Initialize the ToolTip
Arguments:
wdgt: The widget this ToolTip is assigned to
tooltip_font: Font to be used
msg: A static string message assigned to the ToolTip
msgFunc: A function that retrieves a string to use as the ToolTip text
delay: The delay in seconds before the ToolTip appears(may be float)
follow: If True, the ToolTip follows motion, otherwise hides
"""
self.wdgt = wdgt
# The parent of the ToolTip is the parent of the ToolTips widget
self.parent = self.wdgt.master
# Initalise the Toplevel
tk.Toplevel.__init__(self, self.parent, bg='black', padx=1, pady=1)
# Hide initially
self.withdraw()
# The ToolTip Toplevel should have no frame or title bar
self.overrideredirect(True)
# The msgVar will contain the text displayed by the ToolTip
self.msgVar = tk.StringVar()
if msg is None:
self.msgVar.set('No message provided')
else:
self.msgVar.set(msg)
self.msgFunc = msgFunc
self.delay = delay
self.follow = follow
self.visible = 0
self.lastMotion = 0
# The text of the ToolTip is displayed in a Message widget
tk.Message(self, textvariable=self.msgVar, bg='#FFFFDD',
font=tooltip_font,
aspect=1000).grid()
# Add bindings to the widget. This will NOT override
# bindings that the widget already has
self.wdgt.bind('<Enter>', self.spawn, '+')
self.wdgt.bind('<Leave>', self.hide, '+')
self.wdgt.bind('<Motion>', self.move, '+')
def spawn(self, event=None):
"""
Spawn the ToolTip. This simply makes the ToolTip eligible for display.
Usually this is caused by entering the widget
Arguments:
event: The event that called this funciton
"""
self.visible = 1
# The after function takes a time argument in milliseconds
self.after(int(self.delay * 1000), self.show)
def show(self):
"""
Displays the ToolTip if the time delay has been long enough
"""
if self.visible == 1 and time() - self.lastMotion > self.delay:
self.visible = 2
if self.visible == 2:
self.deiconify()
def move(self, event):
"""
Processes motion within the widget.
Arguments:
event: The event that called this function
"""
self.lastMotion = time()
# If the follow flag is not set, motion within the
# widget will make the ToolTip disappear
#
if self.follow is False:
self.withdraw()
self.visible = 1
# Offset the ToolTip 10x10 pixes southwest of the pointer
self.geometry('+%i+%i' % (event.x_root+20, event.y_root-10))
try:
# Try to call the message function. Will not change
# the message if the message function is None or
# the message function fails
self.msgVar.set(self.msgFunc())
except:
pass
self.after(int(self.delay * 1000), self.show)
def hide(self, event=None):
"""
Hides the ToolTip. Usually this is caused by leaving the widget
Arguments:
event: The event that called this function
"""
self.visible = 0
self.withdraw()
def update(self, msg):
"""
Updates the Tooltip with a new message. Added by Rozen
"""
self.msgVar.set(msg)
# ===========================================================
# End of Class ToolTip
# ===========================================================
if __name__ == '__main__':
vp_start_gui()
HERE IS THE ERROR PICTURE:
https://i.stack.imgur.com/eAs6q.png
https://i.stack.imgur.com/7qwDf.png
Thanks
Don't use a mix of tabs and space for indentation, it's not considered a good practice (python specific).
Now to fix it:
Go to terminal and type pip install autopep8
Once it's installed type the following command :
autopep8 -i yourfilename.py
3)You're good to go now!
I am struggling to get a simple GUI to work with python (2.7) on Raspberry Pi (Buster).
I have tried Tkinter and PySimpleGUI but both of these effectively use while loops and I
already have such a loop in my program, which is working without issue.
Both Tkinter and PySimpleGUI block the main loop.
Attempts to run Tkinter and PySimpleGUI in a thread do not seem to work,
various elements are not thread compliant and hang with various error messages.
In any case it appears that once in a thread you can't interact with the GUI widgets
unless you create complicated queues and they are not thread safe.
All I am trying to do is write out the print 'Alert Door statement (last line of the while loop)
into a text field (something pretty / colourful)
and then have an alarm sound (GPIO) and a button which clears the alarm and text field.
Any thoughts apreciated, it appears the available Pi GUIs are just not suitable.
Be gentle, I am a newbie.
def vp_start_gui():
#'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
redalert_support.init(root, top)
root.mainloop()
w = None
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
font13 = "-family {Segoe UI} -size 22"
font14 = "-family {Segoe UI} -size 21"
top.geometry("480x300+267+205")
top.minsize(120, 1)
top.maxsize(1028, 749)
top.resizable(1, 1)
top.title("SecuriCode RedAlert")
top.configure(background="#4339fb")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.333, rely=0.667, height=54, width=177)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#ffff00")
self.Button1.configure(cursor="fleur")
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(font=font14)
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Clear Alarm''')
self.Text1 = tk.Text(top)
self.Text1.place(relx=0.125, rely=0.133, relheight=0.423, relwidth=0.756)
self.Text1.configure(background="white")
self.Text1.configure(font=font13)
self.Text1.configure(foreground="black")
self.Text1.configure(highlightbackground="#d9d9d9")
self.Text1.configure(highlightcolor="black")
self.Text1.configure(insertbackground="black")
self.Text1.configure(selectbackground="#c4c4c4")
self.Text1.configure(selectforeground="black")
self.Text1.configure(wrap="word")
vp_start_gui()
while 1:
#Receive data from LAN device
reply = s.recv(34)
#Receive replies from SMS Gateway
#smsreply = g.recv(34)
#Check for Lan device keep alive replies
if reply.find(alivereply) != -1:
#print 'Device alive'
print reply
#Check for valid Tag strings
if reply.find(tagstring) != -1:
print 'Tag string received'
print reply
#Send SMS alert message
doorcode = reply[5:6]
doornumber = int(doorcode, 16)
#print doornumber
tagcode = reply[8:9]
tagnumber = int(tagcode, 16)
#print tagnumber
print 'Alert Door ' +str(doornumber) + ' Tag ' +str(tagnumber)
Both Tkinter and PySimpleGUI block the main loop.
This is not true always.In my experience the best solution to stop tkinter from blocking the main program's loop is using root_window.update() instead of root_window.mainloop().
Using this will allow you to keep iterating through your while loop and also update your tkinter window.
Hope this helps.
UPDATE
Following your edit I had a look at your code myself.
I changed the function vp_start_gui() and created the root window outside the loop.The main goal of this code is to give you an idea about how to go about implementing your tkinter window correctly.Also about the buttons changing the active background when hovering over it; tkinter.tk Buttons don't have this feature by default.What they really mean by active backgroud is the background color when you click the button.Though there are ways to get this done using tkinter.tk I have showed an easy way to get what you want using tkinter.ttk.
import tkinter as tk
from tkinter import ttk
def vp_update_gui():
#'''Starting point when module is the main routine.'''
global val, w, root
#redalert_support.init(root, top)
root.update()
w = None
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
font13 = "-family {Segoe UI} -size 22"
font14 = "-family {Segoe UI} -size 21"
top.geometry("480x300+267+205")
top.minsize(120, 1)
top.maxsize(1028, 749)
top.resizable(1, 1)
top.title("SecuriCode RedAlert")
top.configure(background="#4339fb")
s = ttk.Style()
s.configure('Kim.TButton', foreground='maroon',activeforeground="yellow")
self.Button1 = ttk.Button(top,style='Kim.TButton',text='''Clear Alarm''')
self.Button1.place(relx=0.333, rely=0.667, height=54, width=177)
self.Text1 = tk.Text(top)
self.Text1.place(relx=0.125, rely=0.133, relheight=0.423, relwidth=0.756)
self.Text1.configure(background="white")
self.Text1.configure(font=font13)
self.Text1.configure(foreground="black")
self.Text1.configure(highlightbackground="#d9d9d9")
self.Text1.configure(highlightcolor="black")
self.Text1.configure(insertbackground="black")
self.Text1.configure(selectbackground="#c4c4c4")
self.Text1.configure(selectforeground="black")
self.Text1.configure(wrap="word")
root = tk.Tk()
top = Toplevel1(root)
while 1:
vp_update_gui()
#Receive data from LAN device
reply = 's.recv(34)'
#Receive replies from SMS Gateway
#smsreply = g.recv(34)
#Check for Lan device keep alive replies
if reply == '-1':
#print 'Device alive'
print (reply)
#Check for valid Tag strings
if reply == '+1':
print ('Tag string received')
print (reply)
#Send SMS alert message
doorcode = reply[5:6]
doornumber = int(doorcode, 16)
#print doornumber
tagcode = reply[8:9]
tagnumber = int(tagcode, 16)
#print tagnumber
print( 'Alert Door ' +str(doornumber) + ' Tag ' +str(tagnumber) )
Your "blocking" problem is easily solving by running your PySimpleGUI program in "async mode". The docs have quite a bit of info about using timeouts on your read call and you'll find tons of demo programs that demonstrate this technique.
Here's a sample bit of code that loops, updating a counter every 100 milliseconds. You could add polling for a hardware condition or some set of conditions instead of updating the text. This is where you would add code to poll something.
import PySimpleGUI as sg
layout = [ [sg.Text('My Window')],
[sg.Text('Will output here', key='-OUT-')],
[sg.Button('Exit')] ]
window = sg.Window('A non-blocking window', layout)
count = 0
while True:
event, values = window.read(timeout=100) # returns every 100 milliseconds
if event == sg.WIN_CLOSED or event == 'Exit':
break
window['-OUT-'].update(f'Count={count}')
count += 1
window.close()
I want to show a message(popup) while python script is executing and automatically disapper when the script done exectuing
import sys
from tkinter import ttk
from tkinter import messagebox
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import new_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
new_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
new_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def smsdata(self):
MsgBox = tk.messagebox.showinfo('Analysing', 'Please wait till the data is being analysed')
* My Script*
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("534x226+710+62")
top.minsize(1, 1)
top.maxsize(1905, 898)
top.resizable(1, 1)
top.title("SMS_Analysis")
top.configure(highlightbackground="#00d81d")
self.Frame1 = tk.Frame(top)
self.Frame1.place(relx=0.0, rely=0.0, relheight=0.996, relwidth=1.002)
self.Frame1.configure(relief='ridge')
self.Frame1.configure(borderwidth="2")
self.Frame1.configure(relief="ridge")
self.Frame1.configure(background="#180bd8")
self.Execute = tk.Button(self.Frame1)
self.Execute.place(relx=0.093, rely=0.089, height=104, width=436)
self.Execute.configure(activebackground="#10ed00")
self.Execute.configure(activeforeground="#ffffff")
self.Execute.configure(background="#10d802")
self.Execute.configure(relief="groove")
self.Execute.configure(text='''Execute''')
self.Execute.configure(command=self.smsdata);
self.Message1 = tk.Message(self.Frame1)
self.Message1.place(relx=0.224, rely=0.756, relheight=0.133
, relwidth=0.563)
self.Message1.configure(text='''Wait For 2 Min''')
self.Message1.configure(width=301)
self.TProgressbar1 = ttk.Progressbar(self.Frame1)
self.TProgressbar1.place(relx=0.093, rely=0.578, relwidth=0.804
, relheight=0.0, height=19)
self.TProgressbar1.configure(length="430")
if __name__ == '__main__':
vp_start_gui()
I want to display Popup While following code is running
def smsdata(self):
MsgBox = tk.messagebox.showinfo('Analysing', 'Please wait till the data is being analysed')
* My Script*
After execution of the popup should disappear.
I have created a MsgBox but the issue is when I press "OK" then script starts executing. I want the popup to appear when code is being executed and vanish when complete executing
new_support
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import new
new.vp_start_gui()
You can use multithreading module or thread module if you want to process multiple commands at the same time if this is the answer that you are searching for.
i am tying to live stream camera in label using tkinter with opencv and python2 but problem is when i click on button only one frame display in label.
#! /usr/bin/env python
# -- coding: utf-8 --
#
# GUI module generated by PAGE version 4.22
# in conjunction with Tcl version 8.6
# May 17, 2019 06:44:40 PM PKT platform: Linux
.
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import gui_support
from Tkinter import *
from PIL import ImageTk, Image
import cv2
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
gui_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
gui_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("1308x647+69+51")
top.title("New Toplevel")
self.menubar = tk.Menu(top,font="TkMenuFont",bg=_bgcolor,fg=_fgcolor)
top.configure(menu = self.menubar)
self.Label1 = tk.Label(top)
self.Label1.place(relx=0.268, rely=0.015, height=31, width=599)
self.Label1.configure(font="-family {Bitstream Vera Sans} -size 21 -weight bold")
self.Label1.configure(text='''Face ID Attendance Marking System''')
self.Label1.configure(width=599)
self.TSeparator1 = ttk.Separator(top)
self.TSeparator1.place(relx=0.245, rely=0.077, relwidth=0.497)
self.TPanedwindow1 = ttk.Panedwindow(top, orient="horizontal")
self.TPanedwindow1.place(relx=0.008, rely=0.139, relheight=0.68
, relwidth=0.982)
self.TPanedwindow1.configure(width=1285)
self.TPanedwindow1_p1 = ttk.Labelframe(width=650, text='Pane 1')
self.TPanedwindow1.add(self.TPanedwindow1_p1)
self.TPanedwindow1_p2 = ttk.Labelframe(text='Pane 2')
self.TPanedwindow1.add(self.TPanedwindow1_p2)
self.__funcid0 = self.TPanedwindow1.bind('<Map>', self.__adjust_sash0)
self.Label2 = tk.Label(self.TPanedwindow1_p1)
self.Label2.place(relx=0.016, rely=0.045, height=411, width=619
, bordermode='ignore')
self.Label2.configure(text='''Label''')
self.Label2.configure(width=619)
self.TButton1 = ttk.Button(top)
self.TButton1.place(relx=0.031, rely=0.835, height=28, width=83)
self.TButton1.configure(takefocus="")
self.TButton1.configure(text='''Tbutton''')
self.TButton1.configure(command = self.cameratk)
def __adjust_sash0(self, event):
paned = event.widget
pos = [640, ]
i = 0
for sash in pos:
paned.sashpos(i, sash)
i += 1
paned.unbind('<map>', self.__funcid0)
del self.__funcid0
def cameratk(self):
cap = cv2.VideoCapture(0)
_, frame = cap.read()
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
self.Label2.imgtk = imgtk
self.Label2.configure(image=imgtk)
self.Label2.after(1, video_stream)
if __name__ == '__main__':
vp_start_gui()
Solved
self.Label2.after(1, video_stream)
Video_Stream Replaced by Function name as self.cameratk
self.Label2.after(1, self.cameratk)
and cap = cv2.VideoCapture(0) outside from the function.