How to embed html codings in python tkinter [duplicate] - python

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 :)

Related

VLC causes buffer when embedded in Python Tkinter Frame

I have been working on a music player app that uses VLC to play songs directly from the internet and has features like seeking and a progress bar. But as the normal tkinter progress bar looks kinda old so I used customtkinter.CTkSlider widget but using this causes buffering. The song plays smoothly on using Tk.Scale.
Here, is the code:
# import external libraries
import vlc
import tkinter as Tk
from tkinter import ttk
import pyautogui
import customtkinter
import pafy
# import standard libraries
import os
from threading import Thread, Event
import time
import platform
import requests
class ttkTimer(Thread):
"""a class serving same function as wxTimer... but there may be better ways to do this
"""
def __init__(self, callback, tick):
Thread.__init__(self)
self.callback = callback
self.stopFlag = Event()
self.tick = tick
self.iters = 0
def run(self):
while not self.stopFlag.wait(self.tick):
self.iters += 1
self.callback()
def stop(self):
self.stopFlag.set()
def get(self):
return self.iters
class Player(Tk.Frame):
"""The main window has to deal with events.
"""
def __init__(self, parent, title=None):
Tk.Frame.__init__(self, parent)
self.parent = parent
if title == None:
title = "tk_vlc"
self.parent.title(title)
# Menu Bar
# File Menu
menubar = Tk.Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Tk.Menu(menubar)
fileMenu.add_command(label="Open", underline=0, command=self.OnOpen)
fileMenu.add_command(label="Exit", underline=1, command=_quit)
menubar.add_cascade(label="File", menu=fileMenu)
# The second panel holds controls
self.player = None
self.videopanel = ttk.Frame(self.parent)
self.canvas = Tk.Canvas(self.videopanel).pack(fill=Tk.BOTH,expand=1)
self.videopanel.pack(fill=Tk.BOTH,expand=1)
ctrlpanel = ttk.Frame(self.parent)
pause = ttk.Button(ctrlpanel, text="Pause", command=self.OnPause)
play = ttk.Button(ctrlpanel, text="Play", command=self.OnPlay)
stop = ttk.Button(ctrlpanel, text="Stop", command=self.OnStop)
volume = ttk.Button(ctrlpanel, text="Volume", command=self.OnSetVolume)
pause.pack(side=Tk.LEFT)
play.pack(side=Tk.LEFT)
stop.pack(side=Tk.LEFT)
volume.pack(side=Tk.LEFT)
self.volume_var = Tk.IntVar()
self.volslider = Tk.Scale(ctrlpanel, variable=self.volume_var, command=self.volume_sel,
from_=0, to=100, orient=Tk.HORIZONTAL, length=100)
self.volslider.pack(side=Tk.LEFT)
ctrlpanel.pack(side=Tk.BOTTOM)
ctrlpanel2 = ttk.Frame(self.parent)
self.scale_var = Tk.DoubleVar()
self.timeslider_last_val = ""
self.timeslider = customtkinter.CTkSlider(ctrlpanel2, variable=self.scale_var, command=self.scale_sel,
from_=0, to=1000, orient=Tk.HORIZONTAL) # This causes buffer
self.timeslider.pack(side=Tk.BOTTOM, fill=Tk.X,expand=1)
self.timeslider_last_update = time.time()
ctrlpanel2.pack(side=Tk.BOTTOM,fill=Tk.X)
# VLC player controls
self.Instance = vlc.Instance()
self.player = self.Instance.media_player_new()
self.timer = ttkTimer(self.OnTimer, 1.0)
self.timer.start()
self.parent.update()
#self.player.set_hwnd(self.GetHandle()) # for windows, OnOpen does does this
def Extract(self,topic):
"""Will play video on following topic, takes about 10 to 15 seconds to load"""
url = 'https://www.youtube.com/results?q=' + topic
count = 0
cont = ''
try:
cont = requests.get(url)
except:
print('Error','Cannot Connect.. Internet not connected or invalid URL or id.')
cont = ''
data = cont.content
data = str(data)
lst = data.split('"')
for i in lst:
count+=1
if i == 'WEB_PAGE_TYPE_WATCH':
break
if lst[count-5] == "/results":
print("Error","No video found.")
return "https://www.youtube.com"+lst[count-5]
def OnExit(self, evt):
"""Closes the window.
"""
self.Close()
def OnOpen(self):
"""Pop up a new dialow window to choose a file, then play the selected file.
"""
# if a file is already running, then stop it.
self.OnStop()
fullname = pafy.new(self.Extract(pyautogui.password(mask="", title="Enter Song Name:", text="Enter Song Name:"))).getbest().url
self.Media = self.Instance.media_new(fullname)
self.player.set_media(self.Media)
# set the window id where to render VLC's video output
if platform.system() == 'Windows':
self.player.set_hwnd(self.GetHandle())
else:
self.player.set_xwindow(self.GetHandle()) # this line messes up windows
# FIXME: this should be made cross-platform
self.OnPlay()
# set the volume slider to the current volume
#self.volslider.SetValue(self.player.audio_get_volume() / 2)
self.volslider.set(self.player.audio_get_volume())
def OnPlay(self):
"""Toggle the status to Play/Pause.
If no file is loaded, open the dialog window.
"""
# check if there is a file to play, otherwise open a
# Tk.FileDialog to select a file
if not self.player.get_media():
self.OnOpen()
else:
# Try to launch the media, if this fails display an error message
if self.player.play() == -1:
self.errorDialog("Unable to play.")
def GetHandle(self):
return self.videopanel.winfo_id()
#def OnPause(self, evt):
def OnPause(self):
"""Pause the player.
"""
self.player.pause()
def OnStop(self):
"""Stop the player.
"""
self.player.stop()
# reset the time slider
self.timeslider.set(0)
def OnTimer(self):
"""Update the time slider according to the current movie time.
"""
if self.player == None:
return
# since the self.player.get_length can change while playing,
# re-set the timeslider to the correct range.
length = self.player.get_length()
dbl = length * 0.001
self.timeslider.config(to=dbl)
# update the time on the slider
tyme = self.player.get_time()
if tyme == -1:
tyme = 0
dbl = tyme * 0.001
self.timeslider_last_val = ("%.0f" % dbl) + ".0"
# don't want to programatically change slider while user is messing with it.
# wait 2 seconds after user lets go of slider
if time.time() > (self.timeslider_last_update + 2.0):
self.timeslider.set(dbl)
def scale_sel(self, evt):
if self.player == None:
return
nval = self.scale_var.get()
sval = str(nval)
if self.timeslider_last_val != sval:
self.timeslider_last_update = time.time()
mval = "%.0f" % (nval * 1000)
self.player.set_time(int(mval)) # expects milliseconds
def volume_sel(self, evt):
if self.player == None:
return
volume = self.volume_var.get()
if volume > 100:
volume = 100
if self.player.audio_set_volume(volume) == -1:
self.errorDialog("Failed to set volume")
def OnToggleVolume(self, evt):
"""Mute/Unmute according to the audio button.
"""
is_mute = self.player.audio_get_mute()
self.player.audio_set_mute(not is_mute)
# update the volume slider;
# since vlc volume range is in [0, 200],
# and our volume slider has range [0, 100], just divide by 2.
self.volume_var.set(self.player.audio_get_volume())
def OnSetVolume(self):
"""Set the volume according to the volume sider.
"""
volume = self.volume_var.get()
# vlc.MediaPlayer.audio_set_volume returns 0 if success, -1 otherwise
if volume > 100:
volume = 100
if self.player.audio_set_volume(volume) == -1:
self.errorDialog("Failed to set volume")
def errorDialog(self, errormessage):
"""Display a simple error dialog.
"""
Tk.tkMessageBox.showerror(self, 'Error', errormessage)
def Tk_get_root():
if not hasattr(Tk_get_root, "root"): #(1)
Tk_get_root.root= Tk.Tk() #initialization call is inside the function
return Tk_get_root.root
def _quit():
print("_quit: bye")
root = Tk_get_root()
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
os._exit(1)
if __name__ == "__main__":
# Create a Tk.App(), which handles the windowing system event loop
root = Tk_get_root()
root.protocol("WM_DELETE_WINDOW", _quit)
player = Player(root, title="tkinter vlc")
# show the player window centred and run the application
root.mainloop()
Kindly help
Regards.

Pygame & Tkinter Musikplayer

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!

Python, Tkinter - root is not defined

I have a class - code below - which works flawlessly when called from if __name__ == '__main__': but when I call it from another .py file it spits an error. Apologies if this is a basic mistake on my part, but I tried a LOT of stuff and nothing seemed to work, would really love some help!
The error:
File "c:\Users\...\test.py", line 6, in <module>
app = Screenshot(root)
File "c:\Users\...\Screenshot.py", line 18, in __init__
self.master_screen = Toplevel(root)
NameError: name 'root' is not defined
The Class:
import time
from tkinter import Toplevel, Canvas, Frame, BOTH, YES, Tk
import pyautogui
import datetime
class Screenshot():
def __init__(self, master):
self.master = master
self.rect = None
self.x = self.y = 0
self.start_x = None
self.start_y = None
self.curX = None
self.curY = None
self.master_screen = Toplevel(root)
self.master_screen.title("Fenify")
self.master_screen.attributes("-transparent", "blue")
self.picture_frame = Frame(self.master_screen)
self.picture_frame.pack(fill=BOTH, expand=YES)
self.createScreenCanvas()
#TakeScreenshot
def takeBoundedScreenShot(self, x1, y1, x2, y2):
...
#Window
def createScreenCanvas(self):
...
#Controls
def on_button_press(self, event):
...
def on_button_release(self, event):
...
def on_right_click(self, event):
...
def on_move_press(self, event):
...
#Exit
def exit_screenshot(self):
...
if __name__ == '__main__':
root = Tk()
app = Screenshot(root)
root.mainloop()
example of calling from another class:
import tkinter
from Screenshot import Screenshot
root = tkinter.Tk()
app = Screenshot(root)
root.mainloop()
You want to set the parent/master of your Toplevel to self.master instead of root. root isn't defined in the scope of the Screenshot class, but the input argument master does point to it.
self.master_screen = Toplevel(self.master)

Python tkinter class 2 buttons, only 1 visible

I wrote a class in python tkinter that you can use to create buttons that change their images on leave, enter and button-1 event.
The script:
from tkinter import *
class ImageButton:
def CreateButton(self, image, root):
# --- image setup ---
self.ImageName = image
self.ButtonRoot = root
self.normal = PhotoImage(file="Images/" + self.ImageName + "/normal.png")
self.hover = PhotoImage(file="Images/" + self.ImageName + "/hover.png")
self.clicked = PhotoImage(file="Images/" + self.ImageName + "/clicked.png")
# --- button setup ---
self.Button = Button(self.ButtonRoot, image=self.normal)
self.Button.bind("<Leave>", self.normal_event)
self.Button.bind("<Enter>", self.hover_event)
self.Button.bind("<Button-1>", self.click_event)
return self.Button
def normal_event(self, event):
self.Button.config(image=self.normal)
def hover_event(self, event):
self.Button.config(image=self.hover)
def click_event(self, event):
self.Button.config(image=self.clicked)
Root = Tk()
Image = ImageButton()
FirstButton = Image.CreateButton("scann_device", Root)
FirstButton.grid(row=0, column=0)
SecondButton = Image.CreateButton("get_device_info", Root)
SecondButton.grid(row=1, column=0)
Root.mainloop()
So if you create a button with that class, you can do anything you want. It only binds it to the events I mentioned above. If you create 1 button, it works and you see it on your window, but if you create 2 buttons and grid/pack them, it wont work. It looks like this. The second button also gets the hitbox of the first button.
You only initiate one instance of Image. Therefore, in your second call to CreateButton(), all class objects (self.normal, self.ImageName, self.Button) are overwritten with the new values.
You are probably better off inheriting a class from the tkinter Button and adding your own functions. See this example:
from tkinter import *
class ImageButton(Button):
def __init__(self, image, root, *args, **kwargs):
super().__init__(root, *args, **kwargs)
# --- image setup ---
self.image_name = image
self.normal = PhotoImage(file="Images/" + self.image_name + "/normal.png")
self.hover = PhotoImage(file="Images/" + self.image_name + "/hover.png")
self.clicked = PhotoImage(file="Images/" + self.image_name + "/clicked.png")
# --- button setup ---
self.config(image=self.normal)
self.bind("<Leave>", self.normal_event)
self.bind("<Enter>", self.hover_event)
self.bind("<Button-1>", self.click_event)
def normal_event(self, event):
self.config(image=self.normal)
def hover_event(self, event):
self.config(image=self.hover)
def click_event(self, event):
self.config(image=self.clicked)
root = Tk()
FirstButton = ImageButton("scann_device", root)
FirstButton.grid(row=0, column=0)
SecondButton = ImageButton("get_device_info", root)
SecondButton.grid(row=1, column=0)
root.mainloop()

pygame.camera "livefeed" inside a tkinter window (on raspbian)

I've looked into embedding a pygame window inside a tkinter window (Reference: Embed Pygame in Tkinter)
I wanted to use this to embed a snapshot (once that works possibly a livefeed) made by the pygame.camera module
In the comments it is said the code should work with Linux (running on raspbian) when commenting out os.environ['SDL_VIDEODRIVER'] = 'windib'
However I can't get the embedding to work nor making a snapshot with pygame, and I can't figure out what's causing the issue. Here's the code I wrote:
import pygame as pg
import pygame.camera
import tkinter as tk
import os
import threading as th
tk.Frame = tk.LabelFrame
def start():
root = tk.Tk()
run = Viewer(root)
return run
class Viewer(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.screen_width = parent.winfo_screenwidth()
self.screen_height = parent.winfo_screenheight()
self.startup(self.screen_width, self.screen_height)
def startup(self, width, height):
self.parent.protocol('WM_DELETE_WINDOW', self.parent.destroy)
Viewer.embed = tk.Frame(self.parent, width=650, height=490)
Viewer.embed.pack(side = tk.LEFT)
self.buttonFrame = tk.Frame(self.parent, width=100, height=490)
self.buttonFrame.pack(side = tk.RIGHT)
self.refresh = tk.Button(self.buttonFrame,
text='Refresh',
command=self.refresh)
self.refresh.pack()
def refresh(self):
self.c = Capture()
self.c.snap()
class Capture(Viewer):
def __init__(self):
os.environ['SDL_WINDOWID'] = str(Viewer.embed.winfo_id())
self.size = (640,480)
self.display = pg.display.set_mode(self.size)
self.clist = pg.camera.list_cameras()
if not self.clist:
raise ValueError("Sorry, no cameras detected.")
self.cam = pg.camera.Camera(self.clist[0], self.size)
self.cam.start()
self.snapshot = pg.surface.Surface(self.size, 0, self.display)
self.event = th.Thread(target=self.eventCatcher)
self.event.start()
def snap(self):
self.snapshot = self.cam.get_image(self.snapshot)
def eventCatcher(self):
closed = False
while not closed:
events = pg.event.get()
for e in events:
if e.type == pg.QUIT:
self.cam.stop()
closed = True
pg.init()
pg.camera.init()
main = start()
main.mainloop()
You have to use pygame after you set os.environ['SDL_WINDOWID']
os.environ['SDL_WINDOWID'] = str(...)
pygame.init()
EDIT: it works on Linux Mint 18.2
import pygame as pg
import pygame.camera
import tkinter as tk
import os
import threading as th
#tk.Frame = tk.LabelFrame
class Viewer(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent # there is self.master which keeps parent
self.parent.protocol('WM_DELETE_WINDOW', self.parent.destroy)
self.screen_width = parent.winfo_screenwidth()
self.screen_height = parent.winfo_screenheight()
self.embed = tk.Frame(self.parent, width=650, height=490)
self.embed.pack(side='left')
self.buttonFrame = tk.Frame(self.parent, width=100, height=490)
self.buttonFrame.pack(side='right')
self.parent.update() # need it to get embed.winfo_id() in Capture
self.c = Capture(self)
self.refreshButton = tk.Button(self.buttonFrame,
text='Refresh',
command=self.refresh)
self.refreshButton.pack()
def refresh(self):
self.c.snap()
class Capture():
def __init__(self, parent):
os.environ['SDL_WINDOWID'] = str(parent.embed.winfo_id())
pg.display.init()
pg.camera.init()
self.size = (640,480)
self.display = pg.display.set_mode(self.size)
self.display.fill(pg.Color(255,255,255))
pg.display.update()
self.clist = pg.camera.list_cameras()
if not self.clist:
raise ValueError("Sorry, no cameras detected.")
print('cameras:', self.clist)
self.cam = pg.camera.Camera(self.clist[0], self.size)
self.cam.start()
self.snapshot = pg.surface.Surface(self.size, 0, self.display)
self.event = th.Thread(target=self.eventCatcher)
self.event.start()
def snap(self):
print('snap ready:', self.cam.query_image())
self.cam.get_image(self.snapshot)
self.display.blit(self.snapshot, self.snapshot.get_rect())
pg.display.update()
def eventCatcher(self):
closed = False
while not closed:
events = pg.event.get()
for e in events:
if e.type == pg.QUIT:
self.cam.stop()
closed = True
root = tk.Tk()
run = Viewer(root)
root.mainloop()

Categories