Using pyopengltk and add another common tkinter function - python

I currently try to create opengl simulation in tkinter, so i found this. The example code provided there :
import time
import tkinter
from OpenGL import GL
from pyopengltk import OpenGLFrame
class AppOgl(OpenGLFrame):
def initgl(self):
"""Initalize gl states when the frame is created"""
GL.glViewport(0, 0, self.width, self.height)
GL.glClearColor(0.0, 1.0, 0.0, 0.0)
self.start = time.time()
self.nframes = 0
def redraw(self):
"""Render a single frame"""
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
tm = time.time() - self.start
self.nframes += 1
print("fps",self.nframes / tm, end="\r" )
if __name__ == '__main__':
root = tkinter.Tk()
app = AppOgl(root, width=320, height=200)
app.pack(fill=tkinter.BOTH, expand=tkinter.YES)
app.animate = 1
app.after(100, app.printContext)
app.mainloop()
I can run it fine but i sligthly confused because i usually use tkinter with this format :
class frontpage(tk.Tk):
def __init__(self,parent):
tk.Tk.__init__(self,parent)
self.parent=parent
'''Creating'''
#Window 1
label1 = tk.Label(self, text = 'App title',bg='blue',fg='white')
frame1 = tk.Frame(self)
''' Some code '''
label1.pack(fill='x')
frame1.pack()
def func1(self):
#some function
if __name__ == '__main__':
frontapp = frontpage(None)
frontapp.title('App v0.1')
frontapp.mainloop()
Given that, is there anyway i could insert normal tkinter item such as frame, button, etc using pyopengltk?

Based on solution suggested by #stovfl, we just need to insert our opengl class into our tkinter class __init__. Then it become :
from __future__ import print_function
import sys, math, time
import tkinter as tk
from OpenGL import GL, GLU
from pyopengltk import OpenGLFrame
class AppOgl(OpenGLFrame):
def initgl(self):
"""Initalize gl states when the frame is created"""
GL.glViewport(0, 0, self.width, self.height)
GL.glClearColor(0.0, 1.0, 0.0, 0.0)
self.start = time.time()
self.nframes = 0
def redraw(self):
"""Render a single frame"""
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
tm = time.time() - self.start
self.nframes += 1
print("fps",self.nframes / tm, end="\r" )
class frontpage(tk.Tk):
def __init__(self,parent):
tk.Tk.__init__(self,parent)
self.parent=parent
open_gl_frame = AppOgl(self, width=320, height=200)
'''Creating'''
#Window 1
label1 = tk.Label(self, text = 'App title',bg='blue',fg='white')
frame1 = tk.Frame(self)
''' Some code '''
open_gl_frame.animate=1 #dont forget this, or your simulation would not animated
open_gl_frame.pack()
label1.pack(fill='x')
frame1.pack()
def func1(self):
pass
if __name__ == '__main__':
frontapp = frontpage(None)
frontapp.title('App v0.1')
frontapp.mainloop()

Related

How to print results iteratively on a canvas or text widget within a GUI made in Python?

I have made a simple GUI that has two buttons for a Square function and Exit button. I want to print the results on the canvas as shown in the expected results.
Here are my codes
from tkinter import *
from PIL import Image,ImageTk
from tkinter import filedialog
from PIL import Image, ImageTk
import os
import cv2
import numpy as np
import time
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
self.button1 = Button(self,text='Square',bg= 'blue',width=15,height=2, command =Square)
self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#Text widget for inserting the result
############################################################################################
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
#Label widget
############################################################################################
self.label3 = Label(self,text="Square",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
def Square(self):
for i in range(1,10):
y = i**2
print(i, y)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='red'
app.title("square")
app.mainloop()
My expected results are given in the image below
Not entirely sure what you are asking. But, if you just want to create text on canvas use canvas.create_text(x, y, text).
from tkinter import *
from PIL import Image,ImageTk
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
self.button1 = Button(self,text='Square',bg= 'blue',width=15,height=2, command=self.Square)
self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#Text widget for inserting the result
############################################################################################
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
self.label3 = Label(self,text="Square",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
def Square(self):
for i in range(1,10):
y = i**2
print(i, y)
c_id = self.canvas.create_text(0, 20, text=f"{i}\t{y}", fill="blue", font="Times 14")
bbox = self.canvas.bbox(c_id)
self.canvas.coords(c_id, 100, bbox[3]*i)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='red'
app.title("square")
app.mainloop()

tkinter- subclass of button not placing on screen from inside another class

I'm making a ide for brainf*ck in python using tkinter and I'm adding a recent projects section but when I'm placing the buttons they do not appear on the screen.
Here is the code for the Scene:
from tkinter import *
from tkinter import filedialog as File
import tkinter as tk
class HoverButton(tk.Button):
def __init__(self, master, **kw):
tk.Button.__init__(self, master=master, **kw)
self.defaultBackground = "#5d5d5d"
self['background'] = self.defaultBackground
self['activebackground'] = "#6d6d6d"
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, e):
self['background'] = "#6d6d6d"
def on_leave(self, e):
self['background'] = self.defaultBackground
class ProjectPage(Frame):
def __init__(self, master, projects=[]):
super().__init__(master)
self.projects = projects
self.buttons = []
self.mstr = self.master.master
self.title = "PesolIde: Projets"
self.width = 800
self.height = 500
self.color = "#4d4d4d"
self.projectFrame = tk.Frame(self.mstr,width=800,height=50,bg="#5d5d5d")
self.newProject = HoverButton(self.mstr,text="New Project", height=1, bg="#6d6d6d")
self.openProject = HoverButton(self.mstr,text="Open Project", height=1,bg="#6d6d6d", command=OpenAsk)
self.projectdisplay = tk.Frame(self.mstr, width=700, height=300, bg="#5d5d5d", highlightbackground="black", highlightthickness=1)
for i in range(len(self.projects)):
self.buttons.append(HoverButton(master, text=self.projects[i].split(':')[0], width=50, height=1))
if len(self.buttons)>=40:
break
self.loaded = False
def show(self):
self.projectFrame.place(x=0, y=0)
self.newProject.place(x=20, y=10)
self.openProject.place(x=120, y=10)
self.projectdisplay.place(x=50,y=100)
self.y = 100
print(len(self.buttons))
for i in range(len(self.buttons)):
print("placing " + str(self.buttons[i]))
self.buttons[i].place(x=50,y=100+(20*i))
self.master.set(title=self.title,width=self.width,height=self.height)
self.master.master['bg'] = self.color
def hide(self):
self.newProject.place_forget()
self.openProject.place_forget()
def load(self):
if not self.loaded:
self.newProject.place_forget()
self.openProject.place_forget()
self.loaded = True
def unload(self):
self.newProject.destroy()
self.openProject.destroy()
def OpenAsk():
name = File.askopenfilename()
and here is the code for main.py:
from tkinter import *
import src.framework.modules.Window.Window as windows
import src.framework.src.Scenes.all as Scenes
import tkinter as tk
root = tk.Tk()
window = windows.window(root, "", 800, 500)
window.place()
projects = open("projects.txt",'r').read().split("\n")
start = Scenes.ProjectPage.ProjectPage(window,projects)
start.show()
window.mainloop()
When I make a HoverButton outside the ProjectPage class in the ProjectPage file, it appears as expected but not when initialised from within the class of directly from the main file.
Here are some screenshots.
The output from running main.py:
The output from running from outside the ProjectPage class with the code on the left:
Try to insert values for relx, rely, relwidth, relheight as attributes in "place" or you can as well insert height, width as attributes for place.
Check out the documentation: https://www.tutorialspoint.com/python/tk_place.htm

'RawTurtle' object has no attribute 'Turtle'

I saw the sorting example in turtle demo which python includes and I would like to add similar animations in my program. My program is based in tkinter and I would like to insert turtle animations in a tkinter canvas (with RawTurtle) so first I tried to create a black box in the canvas and I get the following error message:
AttributeError: 'RawTurtle' object has no attribute 'Turtle'
Here's my code:
import tkinter
from turtle import *
class MyApp():
def __init__(self, parent):
self.p = parent
self.f = tkinter.Frame(self.p).pack()
self.c = tkinter.Canvas(self.f, height = '640', width = '1000')
self.c.pack()
self.t = RawTurtle(self.c)
self.main(5)
def main(self, size):
self.t.size = size
self.t.Turtle.__init__(self, shape="square", visible=False)
self.t.pu()
self.t.shapesize(5, 1.5, 2)
self.t.fillcolor('black')
self.t.st()
if __name__ == '__main__':
root= tkinter.Tk()
frame = MyApp(root)
root.mainloop()
You pretty much have it -- those two settings you were trying to change via the non-existent Turtle() instance method can be handled when creating the RawTurtle:
import tkinter
from turtle import RawTurtle
class MyApp():
def __init__(self, parent):
self.p = parent
self.f = tkinter.Frame(self.p).pack()
self.c = tkinter.Canvas(self.f, height=640, width=1000)
self.c.pack()
self.t = RawTurtle(self.c, shape='square', visible=False)
self.main(5)
def main(self, size):
self.t.size = size # does nothing if stamping with pen up
self.t.penup()
self.t.shapesize(5, 1.5, 2)
self.t.fillcolor('black') # the default
self.t.stamp()
if __name__ == '__main__':
root = tkinter.Tk()
frame = MyApp(root)
root.mainloop()

Dynamic Change label value with global variabel tkinter

With this code I want to make label L3 and L4 change dynamically according to global variabel LED 1 and LED 2, but cant make it work with my code below, anyone have good suggestion for me?
I know it wont work because method init just running once every time I start run my code.
I read some suggestion before using root.after but I cant make it work with my code.
from Tkinter import *
import ttk
from ttk import *
suhu=30
cahaya=50
LED1='-'
LED2='-'
def mqttx():
def on_message(mqttc,obj,msg):
global LED1
global LED2
print "Telah Diterima message : "+msg.payload+" topik "+msg.topic
r.rpush(msg.topic,msg.payload)
datasuhu = r.lrange("suhu",-1,-1)
datacahaya = r.lrange("cahaya",-1,-1)
if msg.topic=="suhu":
if float(msg.payload)<=suhu :
mqttc.publish("2","1",qos=0,retain=False)
LED1="ON"
elif float(msg.payload)>suhu:
mqttc.publish("2","0",qos=0,retain=False)
LED1="OFF"
if msg.topic=="cahaya" :
if float(msg.payload) <=cahaya:
mqttc.publish("1","1",qos=0,retain=False)
LED2="ON"
elif float(msg.payload)>cahaya:
mqttc.publish("1","0",qos=0,retain=False)
LED2="OFF"
mqttc.on_message = on_message
mqttc.connect("localhost",1883)
mqttc.subscribe("suhu")
mqttc.subscribe("cahaya")
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Subcriber")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
self.L3 =Label(self,text="LED 1 : "+LED1)
self.L3.pack
self.L3.grid()
self.L4 =Label(self,text="LED 2 : "+LED2)
self.L4.pack
self.L4.grid()
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
mqttx()
mqttc.loop_start()
main()
Use after() to call function which will change text in labels.
I created test() function to test it without function mqttx()
from Tkinter import *
import ttk
from ttk import *
LED1 = '-'
LED2 = '-'
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
# run first time
self.update()
def initUI(self):
self.parent.title("Subcriber")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
self.L3 = Label(self,text="LED 1 : "+LED1)
self.L3.grid()
self.L4 = Label(self, text="LED 2 : "+LED2)
self.L4.grid()
def update(self):
#print('[DEBUG] update_text')
self.L3['text'] = "LED 1 : " + LED1
self.L4['text'] = "LED 2 : " + LED2
# run again after 500ms (0.5s)
self.after(500, self.update)
def test(root):
import random
global LED1
global LED2
print('[DEBUG] test')
LED1 = str(random.randint(1,10))
LED2 = str(random.randint(1,10))
# run again after 500ms (0.5s)
root.after(500, test, root)
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example(root)
test(root)
root.mainloop()
main()

python tkinter with a simple web wrapper

I am writing a simple python program with a UI, and i can't find out how to put a web page inside the program. I tried searching on Google, but i can't find any simple implementations.
Any links would be great. Just to recap, i just want a simple GUI python program with a webpage embeded inside it, basically like this:
# File: hello1.py
from Tkinter import *
root = Tk()
w = Label(root, text="This is where i was the web page embeded")
w.pack()
root.mainloop()
Thanks,
EDIT:
Solved the problem, used webkit
#!/usr/bin/env python
import gtk
import webkit
import gobject
gobject.threads_init()
win = gtk.Window()
bro = webkit.WebView()
bro.open("http://www.google.com")
win.add(bro)
win.show_all()
gtk.main()
Jack
You can both embed HTML and open full web-pages (with CSS and javascript even) in tkinter. With the cefpython module you can embed a full-blown Chromium browser in a tk window.
from cefpython3 import cefpython as cef
import ctypes
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
import sys
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")
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.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
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="http://www.google.com") #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:
from AppKit import NSApp
import objc
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):
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)
# Back button
back = b'iVBORw0KGgoAAAANSUhEUgAAAGAAAABgBAMAAAAQtmoLAAAAKlBMVEUAAAAyMjIzMzMzMzMyMjIzMzMxMTEzMzMtLS0zMzMkJCQyMjIrKysxMTExeYOJAAAADnRSTlMAgH3/cGlU1BHPDsoMWDQYbKYAAACNSURBVHgB7deBBYBAAIXha4YWaIdXJYlGaJwAzRFojhMarQnO+eWg3g9AvijnXXDZnKuawKpbCEgLA6QOAtLKAKmHgDYIDLuBDDBS4KDA+TsgQmC6IXAZyADpEkA6CogC/AH+SpQIlIAf7v2vYSIGfJBR4ihFmNjx+KHE8AliLjlD6dAFUxqMdX4dcM49/KeCIizV7gUAAAAASUVORK5CYII='
self.back_image = tk.PhotoImage(data=back)
self.back_image = self.back_image.zoom(25).subsample(100)
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 = b'iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAAA1UlEQVR4Ae3cAQbCYBzG4Q6QiI4wYIbtPU1HCAgQSOcLgtBtamHQAb5/43noAu8Pmu37NgAAAAAAAAAAAC0luU7TdNuUMP4lyfv7E6GxefDzMr4IheOL0FiS0zK2CI2N43hcRhahQJJDkqcIhYZh2IsgAiKIgAgi8BPhURiBrut2IoiACCIgggj8WQQR5mHvhRHo+35bEAERBMD4xl8V4/v7iQcw42N842N8L+XxWYrxMb7xMb5TMsZ/GX+Nh/RwTNVBbVxV4LIOXFcDAAAAAAAAAADwAephJFWvaMW3AAAAAElFTkSuQmCC'
self.forward_image = tk.PhotoImage(data=forward)
self.forward_image = self.forward_image.zoom(25).subsample(100)
self.forward_button = tk.Button(self, image=self.forward_image,command=self.go_forward)
self.forward_button.grid(row=0, column=1)
# Reload button
refresh = b'iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAQAAABIkb+zAAADwklEQVR4Ae2aY5jGVhCFZ+3a9iK7+XLPqW23v2rbtm3btm3btm3bbWpN8i0nt83z3Hd+Z+ac6GokEAgEAoFAIBAIBKyIGjkr1sJBuIoP8zV8w6/4Oh/GVTgIayWzRI0yJLiT+COZGjvzZnzLtJ/4Grdg+3gcGRTchqn4oG90bsvHmQ46vsPZycyDke/BgJsUR/IrpkMP3M0lpVaqgE2YFm+ghusNUbyOp9081eQXbqAyIW5hahBXurGz8gs3wOX4KVOjeBuUv+C6TIs2UMfjmVoGvnXLKPnFGWArru9Xzgs8kxu5mX7/53d2xJ2cCytwW57Jl/qx8BO3VfKLMTBVE++tfh9xUtwp/cA+nMbvq15/A9PCDfC8KsW/4IG948og6J0Yh/Pr/CyFG3Bb55b5EvtGY8gQiCfitfRvAAvgp5wiz7hJh/cfw8deDVSmwefZArg8bpNhEo2HW/wZqMGjOQWOkloZAWzgeZ4MuNVz0p9gcFtO8mIgauf72SmA1MoIUfKLM4Dts59u1C4jhEd5+oijdn6iPt1v2GUl34MBbKrTYhdD+R4MPKLSvj5Vk5V8DwZcTybt5jIicDBTjwawh3p9Pu/sMJTvwcD9evCyk+/BQDKanv9UnJ18DwawmEr5gQwb7s3Uv4Gt1BdwgaV8DwZ4gkq5haV8DwZw678TuoWkXOAp9QpNJeWCr6uHOpaUC719NVGLlAu9bo0aS/4KdY0p5YJPl/wjxm3/NpAsLOUCJ6onsKWUC26jfqPnSblwi2cmc+UiatfTaVeRcoH71FdwpBQETlNP+3YRD0tKK9wE/L6QH0Yl0lNct5kUAA7SdfqmEBvwqPW2Su5O9Reqyh1iBTbR9wY7izE8S9dwq4sVE7XoKR2+iTvFkGTm7NGr6bQR25lu7iriNj6Tyb+u9Wjwni6Bq6RWLKjLObZ90Xza7lYzO+BQ8JRsZjePmFPDh+2PmKQWh+RkvViKIO7MO+TjFXHbCHb9bszJ+KlqiLLDLWR5zOqmxStMs+GWEU3RB934AvtyrCH+mPfDj7m5DpJiwTnVWw04/uDEc2V179WfrVCmasL9w232YEMyH07ml0yryWeDGGDSboMZf/+TT9bM8dGdzMKNeIWSruM8qRdP1OmVskEcJTXiEyzFT8zEf+1WE//0TmzU9PdgMrX8R9Rg/RG2Xb7lVjN6dfw3vvJTt4PBVrFZ6/FjQxL/KrY32GX11PytpR+ZzCe1/+P2+2SWP9rvH/qt/f73lsoXcSF3xGLxRGJEIBAIBAKBQCAQCPwM9/tgs3UybYkAAAAASUVORK5CYII='
self.reload_image = tk.PhotoImage(data=refresh)
self.reload_image = self.reload_image.zoom(25).subsample(100)
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)
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()
Try using Tkinterweb!
https://pypi.org/project/tkinterweb/
Demo code:
from tkinterweb import HtmlFrame #import the HTML browser
try:
import tkinter as tk #python3
except ImportError:
import Tkinter as tk #python2
root = tk.Tk() #create the tkinter window
frame = HtmlFrame(root) #create HTML browser
frame.load_website("http://google.com") #load a website
frame.pack(fill="both", expand=True) #attach the HtmlFrame widget to the parent window
root.mainloop()
How about using pywebview ?
It doesn't run in tkinter. but it is simple.
https://pypi.org/project/pywebview/
import webview
webview.create_window('Hello world', 'https://pywebview.flowrl.com/hello')
webview.start()
the simple answer will be is stop wasting your time please learn electron js for making apps b/c after this when you try to compile your tkinter project will be so ugly so learn js then electron my suggestion

Categories

Resources