Call function with a click of a button flask

Im very new to flask and im trying to convert a python tkinter gui app to web. As you can understand i have all the functions made so it would be great if a could call them and pass variables with a single click of a button.

for example:

get_sub_menu is a list generated by a query to the db where it stores [('1','name1'),('2','name2'),('3','name3')]

mod[0] = id

mod[1] = name

html file:

<html><head></head><body>

{% for mod in get_sub_menu %}
<button type="submit">{{ mod[1] }}</button>
{% endfor %}

<!--
when i click in one button he should submit the id(mod[0]) and call function(myid) where myid would be the id submited 
when the button is clicked in order to generate the second list of buttons.
-->

{% for item in function(mod[0]) %}
<button type="submit">{{ item[1] }}</button> #function(mod[0])
{% endfor %}

</body><html>

py file:

def function(myid):

    select * from table where id=myid

    res = cursor.fetchall()

    return res 

should i do this with request or args? can anyone help me with bouth questions in order for me to learn and understand why one is better than the other?

Youtube playlist player

Hi, im trying to set a radio and youtube playlist player

my code works with radio and single youtube link but with playlist it says that the link is unrecognized, can somoene help?

import os
from os import path
from random import randrange
from tkinter.ttk import Combobox
import pafy
import requests
import vlc
import time
from tkinter import *
from tkinter import messagebox,PhotoImage

from bs4 import BeautifulSoup

root = Tk()

global phplay,phpause,phstop
global pausevar
pausevar = ""
phplay = PhotoImage(file=r'img/play.png')
phpause = PhotoImage(file=r'img/pause.png')
phstop = PhotoImage(file=r'img/stop.png')


frmradio = LabelFrame(root, text="Radio Player", padx=5, pady=5, highlightbackground="black", highlightthickness=2)
frmradio.grid(row=0, column=0, sticky=NW, pady=2)



def getradiolist():
    var1 = open("Confs/lstradios.txt", "r").readlines()
    data = []

    for line in var1:
        if len(line) > 1:
            estacao, url, = line.split('<=>')
            data.append(estacao)
    return data

valradio = StringVar()
imp_radio = Combobox(frmradio, textvariable=valradio, height=10, width=47)
imp_radio['values'] = getradiolist()
imp_radio['state'] = 'readonly'
imp_radio.grid(row=1, column=0,columnspan=5, pady=2, sticky="ew")

# define VLC instance
instance = vlc.Instance('--input-repeat=-1', '--fullscreen')
# Define VLC player
player = instance.media_player_new()
instance.log_unset()


def startplayer(pausevar):
    if pausevar == "sim":
        pausevar=""
        player.pause()


    player.stop()
    esta = imp_radio.get()
    if len(esta)>1:
        var1 = open("Confs/lstradios.txt", "r").readlines()
        for line in var1:
            if len(line) > 1:
                if esta in line:
                    estacao, url, = line.split('<=>')
                    break

        if "youtube" in estacao:
            print(url)
            playlist = pafy.get_playlist2(url.strip())
            items = playlist["items"]# getting playlist items

            def loop_play():
                item = items[randrange(len(items))]
                i_pafy = item['pafy']
                y_url = i_pafy.watchv_url
                video = pafy.new(y_url)
                best = video.getbest()

                media = instance.media_new(best.y_url.strip())
                player.set_media(media)
                frmradio.config(text=str(item["title"]))
                player.play()

            loop_play()
        else:
            media = instance.media_new(url.strip())
            player.set_media(media)
            player.play()


        frmradio.config(text=str("Radio Player : Playing: " + estacao))


def stopplauyer():
    player.stop()
    frmradio.config(text=str("Radio Player"))

def pauseplauyer():
    global pausevar
    pausevar = "sim"
    player.pause()
    frmradio.config(text=str("Radio Player : Pause!"))



Button(frmradio, width="150",height="28", text="Play", image=phplay, command=lambda pausevar=pausevar: startplayer(pausevar)).grid(row=0, column=0, sticky=N + S + E + W)
Button(frmradio, width="100",height="28", text="Pause", image=phpause, command=lambda: pauseplauyer()).grid(row=0, column=1, sticky=N + S + E + W)
Button(frmradio, width="100",height="28", text="Stop", image=phstop,command=lambda: stopplauyer()).grid(row=0, column=2, sticky=N + S + E + W)





if __name__ == '__main__':
    root.mainloop()

Listaradios.txt is

youtube <=> https://www.youtube.com/playlist?list=PLr5JVJSLVg79UpgS6gdrcINWt86npzXkz

Mega Hits <=> http://19553.live.streamtheworld.com:80/MEGA_HITS_SC

Im getting the error in playlist2
pafy.util.GdataError: Youtube Error 403: The request cannot be completed because you have exceeded your <a href="/youtube/v3/getting-started#quota">quota</a>.

I have also tryied with playlist and playlist2

move browserframe to labelframe

Hi, i have this script but cant seem to open the browserframe in the correct place

Captura_de_ecra_2021-10-25,_as_11_07_07.png

import ctypes
import platform
from cefpython3 import cefpython as cef
from tkinter import *
import tkinter as tk
import sys

# platforms
WINDOWS = platform.system() == 'Windows'
LINUX = platform.system() == 'Linux'
MAC = platform.system() == 'Darwin'


class BrowserFrame(tk.Frame):
    def __init__(self, master=None, **kw):
        super().__init__(master, **kw)
        self.browser = None
        self.bind('<Configure>', self.on_configure)

    def get_window_handle(self):
        if MAC:
            from AppKit import NSApp
            import objc
            return objc.pyobjc_id(NSApp.windows()[-1].contentView())
        elif self.winfo_id() > 0:
            return self.winfo_id()
        else:
            raise Exception('Could not obtain window handle!')

    def on_configure(self, event):
        if self.browser is None:
            # create the browser and embed it in current frame
            rect = [0, 0, self.winfo_width(), self.winfo_height()]
            cef_winfo = cef.WindowInfo()
            win_id = self.get_window_handle()
            cef_winfo.SetAsChild(win_id, rect)
            self.browser = cef.CreateBrowserSync(cef_winfo, url=urlset)

            # start the browser handling loop
            self.cef_loop()

        # resize the browser
        if WINDOWS:
            ctypes.windll.user32.SetWindowPos(
                self.browser.GetWindowHandle(), 0,
                0, 0, event.width, event.height, 0x0002)
        elif LINUX:
            self.browser.SetBounds(0, 0, event.width, event.height)

    def cef_loop(self):
        cef.MessageLoopWork()
        self.after(10, self.cef_loop)


def main():
    sys.excepthook = cef.ExceptHook  # To shutdown all CEF processes on error

    root = tk.Tk()
    root.minsize(600, 600)
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.geometry("%dx%d+0+0" % (w-550, h-250))
    root.title('Test')

    settings = {}
    if MAC:
        settings["external_message_pump"] = True

    cef.Initialize(settings=settings)

    leftfrm = LabelFrame(root, text="left frame for buttons with links", padx=5, pady=5, highlightbackground="black", highlightthickness=2)
    leftfrm.grid(row=0, column=0, rowspan=99, sticky='nw', pady=2)

    home_browser = LabelFrame(root, text="right frame for browser", padx=5, pady=5, highlightbackground="black", highlightthickness=2)
    home_browser.grid(row=0, column=1, rowspan=99, sticky='ne', pady=2)

    BrowserFrame(home_browser).grid(row=2, column=0, columnspan=9, sticky="ne")

    for x in range(1, 25):
        Label(leftfrm, text=str("Link "+str(x))).grid(row=x,column=0)

    global urlset
    urlset = "http://www.google.com"

    root.mainloop()

if __name__ == '__main__':
    main()

The browser only opens when i resize the window and not in the correct place.
Im using a Mac by the way.

thanks

Setting background color of cell always show black

i have this line to set the background color of a cell but instead of the color i specified it set the cell to black.

Tried with diferent colors to check and it always set it to black.

why is that and how to fix it?

ws['A1'].fill = PatternFill(fgColor="7FFFD4", fill_type="solid")
ws['A1'].fill = PatternFill(start_color="8a2be2", end_color="8a2be2", fill_type="solid")
ws['A1'].fill = PatternFill(start_color="8a2be2", fill_type="solid")
ws['A1'].fill = PatternFill(bgColor="7FFFD4", fill_type="solid")

Anyone know why this is not adding borders to my sheet

Anyone know why this is not adding borders to my sheet?

        thick = Side(border_style="thick", color='FF0707')
        ws['F1'].border = Border(top=thick, left=thick, right=thick, bottom=thick)
        for row in ws['A1:D10']:
            for cell in row:
                cell.border = Border(top=thick, left=thick, right=thick, bottom=thick)

lambda dont pass the correct value

Hi have this loop but insted of send the correct value in the button it always send the original value
this creates the buttons named from 0 to 9, but when i run the button it always prints 8 insted of 8,9,10 etc...

from tkinter import *
from tkinter import ttk

root = Tk()

global gen_reprow,x
gen_reprow=8
x=0

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))

def printd(gena):
    print(gena)


def ger_but():
    for x in range(10):
       ttk.Button(mainframe, width="15", text=x,command=lambda gen=gen_reprow: printd(gen)).grid(column=0, row=x, padx=1, pady=15)
        x += 1
        gen_reprow += 1



ger_but()
if __name__ == "__main__":
    root.mainloop()

web browser inside frame with buttons to go to diferente pages

Got this to open a browser inside a specific frame, and i need it to be changeable, any ideas?

been readin pyqt5 but cant seem to manage this

import sys
from tkinter import Tk, ttk
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

mainwind = Tk()
w, h = mainwind.winfo_screenwidth(), mainwind.winfo_screenheight()
mainwind.geometry("%dx%d+0+0" % (w, h))
mainwind.title("browser")

url = "https://www.google.com"
def seturl(urlbtn):
    url = urlbtn




class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.browser = QWebEngineView()
        self.browser.setUrl(QUrl(url))
        self.setCentralWidget(self.browser)
        self.showNormal()

        # navbar
        navbar = QToolBar()
        self.addToolBar(navbar)

        home_btn = QAction('Home', self)
        home_btn.triggered.connect(self.navigate_home)
        navbar.addAction(home_btn)

        self.url_bar = QLineEdit()
        self.url_bar.returnPressed.connect(self.navigate_to_url)
        navbar.addWidget(self.url_bar)

        self.browser.urlChanged.connect(self.update_url)

    def navigate_home(self):
        self.browser.setUrl(QUrl(url))

    def navigate_to_url(self):
        url = self.url_bar.text()
        self.browser.setUrl(QUrl(url))

    def update_url(self, q):
        self.url_bar.setText(q.toString())




frm_window_left = ttk.Frame(mainwind)
frm_window_left.grid(column=0, row=0, rowspan=99)

frm_browser = ttk.Frame(mainwind)
frm_browser.grid(column=1, row=0, rowspan=99)

frm_window_right = ttk.Frame(mainwind)
frm_window_right.grid(column=2, row=0, rowspan=99)



ttk.Label(frm_window_left, text=":::::::::::::left:::::::::::::").grid(column=0, row=0, padx=10, pady=10)
ttk.Button(frm_window_left, text="url1_L", command=seturl("https://outlook.com/")).grid(column=0, row=1, padx=10,pady=10, ipady=35)
ttk.Button(frm_window_left, text="url2_L", command=seturl("https://www.Facebook.com")).grid(column=0, row=2, padx=10,pady=10, ipady=35)

ttk.Label(frm_browser, text="............................Browser Window Open Here................................\n\n\n\n\n\n\n\n\a").grid(column=0, row=0, padx=10, pady=10)


ttk.Label(frm_window_right, text=":::::::::::::right:::::::::::::").grid(column=0, row=0, padx=10, pady=10)
ttk.Button(frm_window_right, text="url1_R", command=seturl("https://www.google.com/")).grid(column=0, row=1, padx=10,pady=10, ipady=35)
ttk.Button(frm_window_right, text="url2_R", command=seturl("https://www.daniweb.com/")).grid(column=0, row=2, padx=10,pady=10, ipady=35)



app = QApplication(sys.argv)
window = MainWindow()
app.exec_()

thanks

populate tables from txt with specific time frame

Need to make independent charts for current month, last month and since the beginnig of the year.

Been trying to make the table and then make the bar charts, got so far but cant seem to populate my code in order to build the tables with the specific data from a txt.

been playing arround but cant seem to do this, can someone help?

from tkinter import *
import calendar
import datetime
import numpy as np
import matplotlib.pyplot as plt

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))
root.title("week")

dt = datetime.datetime.today()
cd = calendar.Calendar()


file = open("sample.txt")
data = file.read()

lst_last_month=[]
for tipo, data in data:
    datetime_object = datetime.strptime(data, '%b %d %Y %I:%M%p')
    if startdate <= datetime_object <= enddate:
        lst_last_month.append(data)
        lst_last_month.append(tipo)

This is the expected end result

este.png

.py page just for variables

Im new to python , trying to update my self from the time of ASP Classic.
In that time i use to have a page for vars that i included in my main page.

I like that method because i can keep all my vars organized.

I tried to do that with python but allways get errors, yes i tried declare them as global as well but still got errors.

Is there a way to do that with python or is it better to declare them as you go?

thanks

Create Several Frames From A List Populated By A Txt

I would like through a list or dict populated by a text to create a frames, this way I could update an app without having to mess with the code, can someone help me?

Seria algo assim:

vars.txt:

tab1 <-> nome1
tab2 <-> nome2
tab3 <-> nome3
tab4 <-> nome4

tab5 <-> nome5

varlist = open("Confs/vars.txt", "r").readlines()
for line in varlist:
     tab, nome = line.split('<->')   
     tab = ttk.Frame(tabControl)
     tabControl.add(tab, text=nome)
     tabControl.pack(expand=1, fill="both")

 makesubmenu(nome,tab)

can this be done?
thanks