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!
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a map and it is saved as html file.
is there any way i can display it in a application using tkinter?
I saw some answers mentioning tkhtml, but I've found little information about it. If anyone could please give me a light, and a insight of how and where to aim my code...
thank you
Yes, you can both embed HTML and open full webpages (with CSS and javascript even) in tkinter. With the cefpython module you can embed a full-blown Chromium browser in a tk window. Below is a working example of displaying a local HTML file (change the HTML file location at the line commented with #todo)
Update August 2020: this works with Python 2.7 / 3.4 / 3.5 / 3.6 / 3.7
Update March 2021 Python 3.8 and 3.9 are now also supported https://github.com/cztomczak/cefpython/releases/tag/v66.1
# Example of embedding CEF Python browser using Tkinter toolkit.
# This example has two widgets: a navigation bar and a browser.
#
# NOTE: This example often crashes on Mac (Python 2.7, Tk 8.5/8.6)
# during initial app loading with such message:
# "Segmentation fault: 11". Reported as Issue #309.
#
# Tested configurations:
# - Tk 8.5 on Windows/Mac
# - Tk 8.6 on Linux
# - CEF Python v55.3+
#
# Known issue on Linux: When typing url, mouse must be over url
# entry widget otherwise keyboard focus is lost (Issue #255
# and Issue #284).
from cefpython3 import cefpython as cef
import ctypes
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
import sys
import os
import platform
import logging as _logging
# Fix for PyCharm hints warnings
WindowUtils = cef.WindowUtils()
# Platforms
WINDOWS = (platform.system() == "Windows")
LINUX = (platform.system() == "Linux")
MAC = (platform.system() == "Darwin")
# Globals
logger = _logging.getLogger("tkinter_.py")
# Constants
# Tk 8.5 doesn't support png images
IMAGE_EXT = ".png" if tk.TkVersion > 8.5 else ".gif"
class MainFrame(tk.Frame):
def __init__(self, root):
self.browser_frame = None
self.navigation_bar = None
# Root
root.geometry("900x640")
tk.Grid.rowconfigure(root, 0, weight=1)
tk.Grid.columnconfigure(root, 0, weight=1)
# MainFrame
tk.Frame.__init__(self, root)
self.master.title("Tkinter example")
self.master.protocol("WM_DELETE_WINDOW", self.on_close)
self.master.bind("<Configure>", self.on_root_configure)
self.setup_icon()
self.bind("<Configure>", self.on_configure)
self.bind("<FocusIn>", self.on_focus_in)
self.bind("<FocusOut>", self.on_focus_out)
# NavigationBar
self.navigation_bar = NavigationBar(self)
self.navigation_bar.grid(row=0, column=0,
sticky=(tk.N + tk.S + tk.E + tk.W))
tk.Grid.rowconfigure(self, 0, weight=0)
tk.Grid.columnconfigure(self, 0, weight=0)
# BrowserFrame
self.browser_frame = BrowserFrame(self, self.navigation_bar)
self.browser_frame.grid(row=1, column=0,
sticky=(tk.N + tk.S + tk.E + tk.W))
tk.Grid.rowconfigure(self, 1, weight=1)
tk.Grid.columnconfigure(self, 0, weight=1)
# Pack MainFrame
self.pack(fill=tk.BOTH, expand=tk.YES)
def on_root_configure(self, _):
logger.debug("MainFrame.on_root_configure")
if self.browser_frame:
self.browser_frame.on_root_configure()
def on_configure(self, event):
logger.debug("MainFrame.on_configure")
if self.browser_frame:
width = event.width
height = event.height
if self.navigation_bar:
height = height - self.navigation_bar.winfo_height()
self.browser_frame.on_mainframe_configure(width, height)
def on_focus_in(self, _):
logger.debug("MainFrame.on_focus_in")
def on_focus_out(self, _):
logger.debug("MainFrame.on_focus_out")
def on_close(self):
if self.browser_frame:
self.browser_frame.on_root_close()
self.master.destroy()
def get_browser(self):
if self.browser_frame:
return self.browser_frame.browser
return None
def get_browser_frame(self):
if self.browser_frame:
return self.browser_frame
return None
def setup_icon(self):
resources = os.path.join(os.path.dirname(__file__), "resources")
icon_path = os.path.join(resources, "tkinter"+IMAGE_EXT)
if os.path.exists(icon_path):
self.icon = tk.PhotoImage(file=icon_path)
# noinspection PyProtectedMember
self.master.call("wm", "iconphoto", self.master._w, self.icon)
class BrowserFrame(tk.Frame):
def __init__(self, master, navigation_bar=None):
self.navigation_bar = navigation_bar
self.closing = False
self.browser = None
tk.Frame.__init__(self, master)
self.bind("<FocusIn>", self.on_focus_in)
self.bind("<FocusOut>", self.on_focus_out)
self.bind("<Configure>", self.on_configure)
self.focus_set()
def embed_browser(self):
window_info = cef.WindowInfo()
rect = [0, 0, self.winfo_width(), self.winfo_height()]
window_info.SetAsChild(self.get_window_handle(), rect)
self.browser = cef.CreateBrowserSync(window_info,
url="file:///J:\q.htm") #todo
assert self.browser
self.browser.SetClientHandler(LoadHandler(self))
self.browser.SetClientHandler(FocusHandler(self))
self.message_loop_work()
def get_window_handle(self):
if self.winfo_id() > 0:
return self.winfo_id()
elif MAC:
# On Mac window id is an invalid negative value (Issue #308).
# This is kind of a dirty hack to get window handle using
# PyObjC package. If you change structure of windows then you
# need to do modifications here as well.
# noinspection PyUnresolvedReferences
from AppKit import NSApp
# noinspection PyUnresolvedReferences
import objc
# Sometimes there is more than one window, when application
# didn't close cleanly last time Python displays an NSAlert
# window asking whether to Reopen that window.
# noinspection PyUnresolvedReferences
return objc.pyobjc_id(NSApp.windows()[-1].contentView())
else:
raise Exception("Couldn't obtain window handle")
def message_loop_work(self):
cef.MessageLoopWork()
self.after(10, self.message_loop_work)
def on_configure(self, _):
if not self.browser:
self.embed_browser()
def on_root_configure(self):
# Root <Configure> event will be called when top window is moved
if self.browser:
self.browser.NotifyMoveOrResizeStarted()
def on_mainframe_configure(self, width, height):
if self.browser:
if WINDOWS:
ctypes.windll.user32.SetWindowPos(
self.browser.GetWindowHandle(), 0,
0, 0, width, height, 0x0002)
elif LINUX:
self.browser.SetBounds(0, 0, width, height)
self.browser.NotifyMoveOrResizeStarted()
def on_focus_in(self, _):
logger.debug("BrowserFrame.on_focus_in")
if self.browser:
self.browser.SetFocus(True)
def on_focus_out(self, _):
logger.debug("BrowserFrame.on_focus_out")
if self.browser:
self.browser.SetFocus(False)
def on_root_close(self):
if self.browser:
self.browser.CloseBrowser(True)
self.clear_browser_references()
self.destroy()
def clear_browser_references(self):
# Clear browser references that you keep anywhere in your
# code. All references must be cleared for CEF to shutdown cleanly.
self.browser = None
class LoadHandler(object):
def __init__(self, browser_frame):
self.browser_frame = browser_frame
def OnLoadStart(self, browser, **_):
if self.browser_frame.master.navigation_bar:
self.browser_frame.master.navigation_bar.set_url(browser.GetUrl())
class FocusHandler(object):
def __init__(self, browser_frame):
self.browser_frame = browser_frame
def OnTakeFocus(self, next_component, **_):
logger.debug("FocusHandler.OnTakeFocus, next={next}"
.format(next=next_component))
def OnSetFocus(self, source, **_):
logger.debug("FocusHandler.OnSetFocus, source={source}"
.format(source=source))
return False
def OnGotFocus(self, **_):
"""Fix CEF focus issues (#255). Call browser frame's focus_set
to get rid of type cursor in url entry widget."""
logger.debug("FocusHandler.OnGotFocus")
self.browser_frame.focus_set()
class NavigationBar(tk.Frame):
def __init__(self, master):
self.back_state = tk.NONE
self.forward_state = tk.NONE
self.back_image = None
self.forward_image = None
self.reload_image = None
tk.Frame.__init__(self, master)
resources = os.path.join(os.path.dirname(__file__), "resources")
# Back button
back_png = os.path.join(resources, "back"+IMAGE_EXT)
if os.path.exists(back_png):
self.back_image = tk.PhotoImage(file=back_png)
self.back_button = tk.Button(self, image=self.back_image,
command=self.go_back)
self.back_button.grid(row=0, column=0)
# Forward button
forward_png = os.path.join(resources, "forward"+IMAGE_EXT)
if os.path.exists(forward_png):
self.forward_image = tk.PhotoImage(file=forward_png)
self.forward_button = tk.Button(self, image=self.forward_image,
command=self.go_forward)
self.forward_button.grid(row=0, column=1)
# Reload button
reload_png = os.path.join(resources, "reload"+IMAGE_EXT)
if os.path.exists(reload_png):
self.reload_image = tk.PhotoImage(file=reload_png)
self.reload_button = tk.Button(self, image=self.reload_image,
command=self.reload)
self.reload_button.grid(row=0, column=2)
# Url entry
self.url_entry = tk.Entry(self)
self.url_entry.bind("<FocusIn>", self.on_url_focus_in)
self.url_entry.bind("<FocusOut>", self.on_url_focus_out)
self.url_entry.bind("<Return>", self.on_load_url)
self.url_entry.bind("<Button-1>", self.on_button1)
self.url_entry.grid(row=0, column=3,
sticky=(tk.N + tk.S + tk.E + tk.W))
tk.Grid.rowconfigure(self, 0, weight=100)
tk.Grid.columnconfigure(self, 3, weight=100)
# Update state of buttons
self.update_state()
def go_back(self):
if self.master.get_browser():
self.master.get_browser().GoBack()
def go_forward(self):
if self.master.get_browser():
self.master.get_browser().GoForward()
def reload(self):
if self.master.get_browser():
self.master.get_browser().Reload()
def set_url(self, url):
self.url_entry.delete(0, tk.END)
self.url_entry.insert(0, url)
def on_url_focus_in(self, _):
logger.debug("NavigationBar.on_url_focus_in")
def on_url_focus_out(self, _):
logger.debug("NavigationBar.on_url_focus_out")
def on_load_url(self, _):
if self.master.get_browser():
self.master.get_browser().StopLoad()
self.master.get_browser().LoadUrl(self.url_entry.get())
def on_button1(self, _):
"""Fix CEF focus issues (#255). See also FocusHandler.OnGotFocus."""
logger.debug("NavigationBar.on_button1")
self.master.master.focus_force()
def update_state(self):
browser = self.master.get_browser()
if not browser:
if self.back_state != tk.DISABLED:
self.back_button.config(state=tk.DISABLED)
self.back_state = tk.DISABLED
if self.forward_state != tk.DISABLED:
self.forward_button.config(state=tk.DISABLED)
self.forward_state = tk.DISABLED
self.after(100, self.update_state)
return
if browser.CanGoBack():
if self.back_state != tk.NORMAL:
self.back_button.config(state=tk.NORMAL)
self.back_state = tk.NORMAL
else:
if self.back_state != tk.DISABLED:
self.back_button.config(state=tk.DISABLED)
self.back_state = tk.DISABLED
if browser.CanGoForward():
if self.forward_state != tk.NORMAL:
self.forward_button.config(state=tk.NORMAL)
self.forward_state = tk.NORMAL
else:
if self.forward_state != tk.DISABLED:
self.forward_button.config(state=tk.DISABLED)
self.forward_state = tk.DISABLED
self.after(100, self.update_state)
if __name__ == '__main__':
logger.setLevel(_logging.INFO)
stream_handler = _logging.StreamHandler()
formatter = _logging.Formatter("[%(filename)s] %(message)s")
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
logger.info("CEF Python {ver}".format(ver=cef.__version__))
logger.info("Python {ver} {arch}".format(
ver=platform.python_version(), arch=platform.architecture()[0]))
logger.info("Tk {ver}".format(ver=tk.Tcl().eval('info patchlevel')))
assert cef.__version__ >= "55.3", "CEF Python v55.3+ required to run this"
sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error
root = tk.Tk()
app = MainFrame(root)
# Tk must be initialized before CEF otherwise fatal error (Issue #306)
cef.Initialize()
app.mainloop()
cef.Shutdown()
I've managed to render simple html tags using the link provided by #j_4321
just pip3 install tkinterhtml
and, from the package example:
from tkinterhtml import HtmlFrame
import tkinter as tk
root = tk.Tk()
frame = HtmlFrame(root, horizontal_scrollbar="auto")
frame.set_content("<html></html>")
If you have the content save in a file, or manually input. OR:
frame.set_content(urllib.request.urlopen("http://thonny.cs.ut.ee").read().decode())
to request and render it.
Hope it helps :)
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.
I'm just adding 1 def with 2 lines of code before it gets indentation error. I'm trying to modify the code that generated from PAGE Tkinter GUI editor for login message box. I really don't know why this happens.
I did the exact same code as this guy on youtube and I tried to move the def into the far-most left neither right.
So what I'm trying to add is. def cancelLogin() inside the login page class. It shows me indentation error on def init(). Please help me to figure this out.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 4.20
# in conjunction with Tcl version 8.6
# Feb 07, 2019 05:38:55 AM EST platform: Linux
import sys
import tkMessageBox
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 jta_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Login_page (root)
jta_support.init(root, top)
root.mainloop()
w = None
def create_Login_page(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Login_page (w)
jta_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Login_page():
global w
w.destroy()
w = None
class Login_page:
def cancelLogin(self):
msg=tkMessageBox.askyesno("Login page","Are you sure , you want to cancel login?")
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'
font11 = "-family {DejaVu Sans} -size 10 -weight bold -slant " \
"roman -underline 0 -overstrike 0"
font17 = "-family {DejaVu Sans} -size 13 -weight bold -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)])
top.geometry("584x457+1039+55")
top.title("JTA Login")
top.configure(relief="ridge")
top.configure(background="#201856")
top.configure(highlightbackground="#000000")
self.btnLogin = tk.Button(top)
self.btnLogin.place(relx=0.634, rely=0.744, height=54, width=101)
self.btnLogin.configure(background="#201856")
self.btnLogin.configure(borderwidth="0")
self.btnLogin.configure(font=font11)
self.btnLogin.configure(highlightbackground="#201856")
self._img1 = tk.PhotoImage(file="../../Downloads/button.png")
self.btnLogin.configure(image=self._img1)
self.btnLogin.configure(padx="6m")
self.btnLogin.configure(pady="3m")
self.btnLogin.configure(text='''Login''')
self.btnLogin.configure(width=101)
self.btnExit = tk.Button(top)
self.btnExit.place(relx=0.223, rely=0.744, height=55, width=97)
self.btnExit.configure(activebackground="#ffffff")
self.btnExit.configure(background="#201856")
self.btnExit.configure(borderwidth="0")
self.btnExit.configure(font=font11)
self.btnExit.configure(highlightbackground="#201856")
self._img2 = tk.PhotoImage(file="../../Downloads/button(1).png")
self.btnExit.configure(image=self._img2)
self.btnExit.configure(padx="6m")
self.btnExit.configure(pady="3m")
self.btnExit.configure(text='''Exit''')
self.btnExit.configure(width=97)
self.txtUsername = tk.Entry(top)
self.txtUsername.place(relx=0.462, rely=0.372, height=40, relwidth=0.342)
self.txtUsername.configure(background="white")
self.txtUsername.configure(font="TkFixedFont")
self.txtPassword = tk.Entry(top)
self.txtPassword.place(relx=0.462, rely=0.547, height=40, relwidth=0.342)
self.txtPassword.configure(background="white")
self.txtPassword.configure(font="TkFixedFont")
self.txtPassword.configure(selectbackground="#c4c4c4")
self.Label1 = tk.Label(top)
self.Label1.place(relx=0.205, rely=0.372, height=40, width=100)
self.Label1.configure(background="#201856")
self.Label1.configure(font=font17)
self.Label1.configure(foreground="#ffffff")
self.Label1.configure(text='''Username''')
self.Label1_3 = tk.Label(top)
self.Label1_3.place(relx=0.205, rely=0.547, height=40, width=100)
self.Label1_3.configure(activebackground="#f9f9f9")
self.Label1_3.configure(background="#201856")
self.Label1_3.configure(font=font17)
self.Label1_3.configure(foreground="#ffffff")
self.Label1_3.configure(text='''Password''')
self.menubar = tk.Menu(top,font="TkMenuFont",bg=_bgcolor,fg=_fgcolor)
top.configure(menu = self.menubar)
self.TLabel1 = ttk.Label(top)
self.TLabel1.place(relx=0.154, rely=0.022, height=131, width=423)
self.TLabel1.configure(background="#201856")
self.TLabel1.configure(foreground="#000000")
self.TLabel1.configure(font="TkDefaultFont")
self.TLabel1.configure(relief='flat')
self.TLabel1.configure(text='''Tlabel''')
self.TLabel1.configure(width=423)
self._img3 = tk.PhotoImage(file="./jtalogo.png")
self.TLabel1.configure(image=self._img3)
if __name__ == '__main__':
vp_start_gui()
without the "def cancelLogin()" it works fine as usual
actual result :
File "./jta.py", line 52
def init(self, top=None):
^
IndentationError: unindent does not match any outer indentation level
You can try:
grep -C 7 "__init" YOUR_FILE.py | tr ' \t' '.*'
This will translate spaces into dots, and tabs into stars. Then you can check if there is a mismatch there.
This is the output when I tried it on the code you posted (from the question source):
$ grep -C 7 "__init" test.py | tr ' \t' '.*'
........w.=.None
....
....class.Login_page:
....
....*def.cancelLogin(self):
....**msg=tkMessageBox.askyesno("Login.page","Are.you.sure.,.you.want.to.cancel.login?")
....
........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'.
As stated by #tobias_k, there are tabs and spaces mixed in the lines you added.
I am using tkinter and i have 2 .py files, one called "account" and another called "account_support" im trying to build the gui in the "account.py" and then have all the functions related to that gui in "account_support.py"
this is account.py
import sys
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = 0
except ImportError:
import tkinter.ttk as ttk
py3 = 1
import account_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = Tk()
top = Add_Account (root)
account_support.init(root, top)
root.mainloop()
w = None
def create_Add_Account(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = Toplevel (root)
top = Add_Account (w)
account_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Add_Account():
global w
w.destroy()
w = None
class Add_Account:
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 = '#d9d9d9' # X11 color: 'gray85'
font9 = "-family {DejaVu Sans} -size 0 -weight normal -slant " \
"roman -underline 0 -overstrike 0"
top.geometry("400x200+407+266")
top.title("Add Account")
top.configure(highlightcolor="black")
self.menubar = Menu(top,font=font9,bg=_bgcolor,fg=_fgcolor)
top.configure(menu = self.menubar)
self.accName = Entry(top)
self.accName.place(relx=0.35, rely=0.3, relheight=0.11, relwidth=0.44)
self.accName.configure(background="white")
self.accName.configure(font="TkFixedFont")
self.accName.configure(selectbackground="#c4c4c4")
self.Label1 = Label(top)
self.Label1.place(relx=0.25, rely=0.1, height=38, width=176)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(text='''Add Account''')
self.Label2 = Label(top)
self.Label2.place(relx=0.03, rely=0.3, height=18, width=126)
self.Label2.configure(activebackground="#f9f9f9")
self.Label2.configure(text='''Account Name:''')
self.key = Entry(top)
self.key.place(relx=0.35, rely=0.5, relheight=0.11, relwidth=0.44)
self.key.configure(background="white")
self.key.configure(font="TkFixedFont")
self.key.configure(selectbackground="#c4c4c4")
self.Label3 = Label(top)
self.Label3.place(relx=0.15, rely=0.5, height=21, width=76)
self.Label3.configure(activebackground="#f9f9f9")
self.Label3.configure(text='''CMA Key:''')
self.add = Button(top)
self.add.place(relx=0.53, rely=0.7, height=26, width=107)
self.add.configure(activebackground="#d9d9d9")
self.add.configure(command=account_support.addaccount)
self.add.configure(text='''Add Account''')
self.helpButton = Button(top)
self.helpButton.place(relx=0.8, rely=0.5, height=16, width=17)
self.helpButton.configure(activebackground="#d9d9d9")
self.helpButton.configure(command=account_support.question)
self.helpButton.configure(text='''?''')
if __name__ == '__main__':
vp_start_gui()
and then for account_support.py
import sys
import webbrowser
import tkMessageBox
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = 0
except ImportError:
import tkinter.ttk as ttk
py3 = 1
def addaccount():
import account
cmakey = account.Entry.key.get()
acc = account.Entry.accName.get()
print acc
print cmakey
sys.stdout.flush()
def question():
tkMessageBox.showinfo(title="CMA Key", message="")
sys.stdout.flush()
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 account
account.vp_start_gui()
when i try to get the value of account.py's key entry
with
def addaccount():
import account
cmakey = account.Entry.key.get()
acc = account.Entry.accName.get()
print acc
print cmakey
sys.stdout.flush()
i get the error
File "/home/silicaandpina/VitaTools/psvimgtools-0.1-linux64/gui/psvimgtools/account_support.py", line 29, in addaccount
cmakey = account.Entry.key.get()
AttributeError: class Entry has no attribute 'key'
When you're executing
cmakey = account.Entry.key.get()
acc = account.Entry.accName.get()
you're trying to access the key property of the Entry class of Tkinter in your module account. As you can tell by the error message, the Entry class doesn't have a property called key.
The Solution
Change your addaccount function to
def addaccount(cmakey, acc):
print acc
print cmakey
sys.stdout.flush()
As you can see, you're now receiving two parameters that are already the strings you want to use. Now, in account, change the button configuration line to
self.add.configure(command=lambda: account_support.addaccount(self.key.get(), self.accName.get()))