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:
playlist = pafy.get_playlist(url)
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()) # por testar ainda
player.set_media(media)
frmradio.config(text=str(playlist["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()
getting this error:
Exception in Tkinter callback Traceback (most recent call last):
File
"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/init.py",
line 1892, in call
return self.func(*args) File "/Users/ricardosimoes/PycharmProjects/OCPP/yplayer.py", line 105, in
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)
File "/Users/ricardosimoes/PycharmProjects/OCPP/yplayer.py", line 70,
in startplayer
playlist = pafy.get_playlist2(url) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pafy/playlist.py",
line 316, in get_playlist2
return Playlist.from_url(playlist_url, basic, gdata, size, callback) File
"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pafy/playlist.py",
line 175, in from_url
t = cls(url, basic, gdata, size, callback) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pafy/playlist.py",
line 146, in init
raise ValueError(err % playlist_url) ValueError: Unrecognized playlist url:
https://www.youtube.com/playlist?list=PLr5JVJSLVg79UpgS6gdrcINWt86npzXkz
Listaradios.txt is
youtube <=> https://www.youtube.com/playlist?list=PLr5JVJSLVg79UpgS6gdrcINWt86npzXkz
Mega Hits <=> http://19553.live.streamtheworld.com:80/MEGA_HITS_SC
Related
Good evening,
I'm trying to do a little program with a GUI in python with Tkinter.
import tkinter as tk
import tkinter.font as tkFont
class WindowCreator:
def __init__(self, root):
user_Ids = []
# setting title
root.title("Instagram Giveaway auto Filler")
# setting window size
width = 318
height = 395
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
label_title = tk.Label(root)
label_title["bg"] = "#000000"
label_title["fg"] = "#ffd700"
label_title["text"] = "Instagram Giveaway Auto Filler"
label_title.place(x=50, y=10, width=201, height=31)
label_urlPost = tk.Label(root)
label_urlPost["bg"] = "#000000"
label_urlPost["fg"] = "#ffd700"
label_urlPost["text"] = "URL to post"
label_urlPost.place(x=0, y=70, width=70, height=25)
entry_urlPost = tk.Entry(root)
entry_urlPost["borderwidth"] = "1px"
entry_urlPost["fg"] = "#333333"
entry_urlPost["text"] = "Entry"
entry_urlPost.place(x=0, y=90, width=310, height=30)
list_userIds = tk.Listbox(root)
list_userIds["borderwidth"] = "1px"
list_userIds["fg"] = "#333333"
list_userIds.place(x=0, y=130, width=132, height=251)
button_addId = tk.Button(root)
button_addId["text"] = "New id"
button_addId.place(x=140, y=320, width=70, height=25)
button_addId["command"] = lambda: button_addId_command(user_Ids, root)
button_comment = tk.Button(root)
button_comment["text"] = "Comment"
button_comment.place(x=140, y=350, width=70, height=25)
button_comment["command"] = button_comment_command
label_loggedIn = tk.Label(root)
label_loggedIn["text"] = "Logged in: "
label_loggedIn.place(x=150, y=150, width=70, height=25)
label_postActive = tk.Label(root)
label_postActive["text"] = "Post active?"
label_postActive.place(x=150, y=190, width=70, height=25)
label_nrEntries = tk.Label(root)
label_nrEntries["text"] = "Number of Entries :"
label_nrEntries.place(x=150, y=230, width=110, height=30)
entry_nrEntries = tk.Entry(root)
entry_nrEntries["text"] = "Entry"
entry_nrEntries.place(x=270, y=230, width=33, height=30)
check_loggedIn = tk.Checkbutton(root)
check_loggedIn["text"] = ""
check_loggedIn.place(x=210, y=150, width=41, height=30)
check_loggedIn["offvalue"] = "0"
check_loggedIn["onvalue"] = "1"
check_loggedIn["command"] = check_loggedIn_command
check_postActive = tk.Checkbutton(root)
check_postActive["text"] = ""
check_postActive.place(x=210, y=190, width=41, height=30)
check_postActive["offvalue"] = "0"
check_postActive["onvalue"] = "1"
check_postActive["command"] = check_postActive_command
button_login = tk.Button(root)
button_login["text"] = "Login"
button_login.place(x=250, y=150, width=44, height=30)
button_login["command"] = button_login_command
user_Ids = read_user_from_file("C:/Users/bruno/OneDrive/Documentos/userIds.txt")
for users in user_Ids:
list_userIds.insert('end', users)
def refresh_user_list(self, user_list):
global user_Ids
for users in user_list:
root.list_userIds.insert('end', users)
def read_user_from_file(file_path):
user_txt = open(file_path, 'r')
userIds = user_txt.readlines()
return userIds
#staticmethod
def button_comment_command():
print("command")
#staticmethod
def check_loggedIn_command():
print("command")
#staticmethod
def check_postActive_command():
print("command")
#staticmethod
def button_login_command():
print("command")
def add_user_id(new_user, user_list, root, main_root):
print(new_user)
print(user_list)
user_list.append(new_user)
print(user_list)
main_root.refresh_user_list(main_root, user_list)
root.destroy()
def button_addId_command(user_list, main_root):
root2 = tk.Toplevel(main_root)
label_title = tk.Label(root2, text="Insert the new ID you want to add to the list ")
entry_userID = tk.Entry(root2)
button_register = tk.Button(root2, text="Register",
command=lambda: add_user_id(entry_userID.get(), user_list, root2, main_root))
label_title.pack()
entry_userID.pack()
button_register.pack()
root2.mainloop
if __name__ == "__main__":
root = tk.Tk()
windows = WindowCreator(root)
root.mainloop()
When I try to add a new user, I click the New Id button, and then a new windows pops up. In that new window, i've a entry widget and a button. I want to, when I click the register button in that new windows, to acess refresh_user_list, so I can refresh the ListBox widget of the first window list_userIds.
I'm having several troubles with passing objects, and acessing then within other scope.
I can't find a proper website that explains it. Can someone help me?
I tried to reduce the amount of code to post, but I couldn't
I tried to pass the objects as parameters ( the root ob
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\bruno\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\bruno\PycharmProjects\InstagramCommentBot\WindowCreator.py", line 135, in <lambda>
button_register = tk.Button(root2, text="Register", command= lambda : add_user_id(entry_userID.get(), user_list, root2, main_root))
File "C:\Users\bruno\PycharmProjects\InstagramCommentBot\WindowCreator.py", line 127, in add_user_id
main_root.refresh_user_list(main_root,user_list)
File "C:\Users\bruno\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2354, in __getattr__
return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'refresh_user_list'
jects of Tk()) but im always getting the error
I am working on my own UI. For now I have just shaped the main screen.
But what I need to do is to run some functions in background while the UI is working and the user is using the UI(i.e. some functions get activated and the user gets redirected to another screen).
I have tried the function that uses multiprocessing module:
def runInParallel(self, *fns):
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()
But unfortunately it does not work, and UI isn't updating.
I have conducted a trial for this method(experimentally) but for some reason when I run this function with arguments self.runInParallel(self.xtb_main_screen, self.getAllSymbols_xtb_api) inside log_in_xtb_api function after clicking log in button another instance of the UI just opens up.
Below is the code for the UI class.
What I want to achieve is to get functions like getAllSymbols or getChartLastRequest, work always when the UI is running.
For the first time when launching the program it gots to download the data for the first time. But after the startup I need to actualise the data every 1,5,15 or etc [minutes].
So my UI can't be constanly lagged due to the code execution.
How do I make any function I want run in parallel/background so the UI won't lag?
This is code for the UI class:
Note that to use the functions like log_in_xtb_api or others from xtb broker api, you need to download the wrapper connector and import it and iside it change ports from 5112 and 5113 to 5124 and 5125 if you have a demo account or leave them as they are if you have real account:
http://developers.xstore.pro/api/wrappers/2.5.0
class UI:
def __init__(self):
self.UI_main = tk.Tk()
self.width_screen, self.height_screen = resolution()
self.canvas_main = tk.Canvas(self.UI_main, height=self.height_screen, width=self.width_screen)
self.canvas_main.pack()
self.login_screen()
self.UI_main.mainloop()
def login_screen(self):
self.frame_login = Frame(self.canvas_main, bg='#131d47')
self.frame_login.pack()
self.frame_login.place(relx=0.5, rely=0.5, anchor=CENTER)
self.login_font = tkFont.Font(family='Calibri', size=30)
self.login_xtb_btn = tk.Button(self.frame_login, text='Log in to XTB', width=25, height=2,
command=self.login_xtb_ui)
self.login_xtb_btn['font'] = self.login_font
self.login_xtb_btn.pack()
self.login_tradingview_btn = tk.Button(self.frame_login, text='Log in to Tradingview', width=25, height=2,
command=self.login_tradingview_choose)
self.login_tradingview_btn['font'] = self.login_font
self.login_tradingview_btn.pack()
def login_xtb_ui(self):
for widgets in self.canvas_main.winfo_children():
widgets.destroy()
self.login_xtb_font = tkFont.Font(family='Calibri', size=25)
self.xtb_login = StringVar()
self.xtb_login.set("Enter user ID")
self.xtb_password = StringVar()
self.xtb_password.set("Enter password here")
self.frame_xtb_login = Frame(self.canvas_main)
self.frame_xtb_login.pack()
self.frame_xtb_login.place(relx=0.5, rely=0.5, anchor=CENTER)
self.xtb_login_entry = Entry(self.frame_xtb_login, textvariable=self.xtb_login, width=25)
self.xtb_login_entry.pack()
self.xtb_login_entry['font'] = self.login_xtb_font
self.xtb_password_entry = Entry(self.frame_xtb_login, textvariable=self.xtb_password, width=25)
self.xtb_password_entry.pack()
self.xtb_password_entry['font'] = self.login_xtb_font
self.xtb_log_in_btn = tk.Button(self.frame_xtb_login, text='Log in', command=self.xtb_log_in)
self.xtb_log_in_btn.pack()
self.xtb_log_in_btn['font'] = self.login_xtb_font
return 'apple'
def xtb_log_in(self):
self.user_id_xtb = self.xtb_login_entry.get()
self.password_xtb = self.xtb_password_entry.get()
'''
self.host = 'xapi.xtb.com'
self.port = 5112
self.host = socket.getaddrinfo(self.host, self.port)[0][4][0]
self.s = socket.socket()
self.s.connect((self.host, self.port))
self.s = ssl.wrap_socket(self.s)
self.END = b'\n\n'
'''
self.log_in_xtb_api(userId=self.user_id_xtb, password=self.password_xtb)
def xtb_main_screen(self):
for widgets in self.canvas_main.winfo_children():
widgets.destroy()
canvas_top_height = math.floor(0.07 * self.height_screen)
canvas_charting_tools_width = math.floor(0.03 * self.width_screen)
canvas_charting_tools_height = self.height_screen - canvas_top_height # takes full screen
paned_window_charting_main_width = self.width_screen - canvas_charting_tools_width
paned_window_charting_main_height = self.height_screen - canvas_top_height
canvas_charting_top_width = self.width_screen - canvas_charting_tools_width
canvas_charting_top_height = self.height_screen - canvas_top_height - math.floor(0.3 * self.height_screen)
canvas_charting_bottom_width = self.width_screen - canvas_charting_tools_width
canvas_charting_bottom_height = self.height_screen - canvas_charting_top_height
canvas_charting_indicators_width = math.floor(0.14 * self.width_screen)
canvas_charting_indicators_height = self.height_screen - canvas_top_height - math.floor(0.3 * self.height_screen)
canvas_charting_chart_width = math.floor(0.65 * self.width_screen)
canvas_charting_chart_height = self.height_screen - canvas_top_height - math.floor(0.3 * self.height_screen)
paned_window_charting_downloads_info_width = self.width_screen - canvas_charting_tools_width - canvas_charting_indicators_width - canvas_charting_chart_width
paned_window_charting_downloads_info_height = canvas_charting_chart_height
canvas_charting_downloads_width = paned_window_charting_downloads_info_width
canvas_charting_downloads_height = math.floor(0.5 * paned_window_charting_downloads_info_height)
canvas_charting_info_width = paned_window_charting_downloads_info_width
canvas_charting_info_height = paned_window_charting_downloads_info_height - canvas_charting_downloads_height
menu_btn_width = 20
menu_btn_height = math.floor(0.7 * canvas_top_height)
menu_xtb_btn_font = tkFont.Font(family='Calibri', size=20)
# Canvas top xtb main aka Menu
# Contains:
# Charting screen
# Symbol search
# Trading Bot
# neural nets
# Machine learning
self.canvas_top_xtb_main = Canvas(self.canvas_main, width=self.width_screen, height=canvas_top_height, bg='#131d47')
self.canvas_top_xtb_main.pack()
# position (0.0, 0.0) top
self.canvas_top_xtb_main.place(relx=0.0, rely=0.0, anchor=NW)
self.frame_menu_xtb_main_top = Frame(self.canvas_top_xtb_main)
self.frame_menu_xtb_main_top.pack(expand=False)
self.frame_menu_xtb_main_top.place(relx=0.0, rely=0.0, anchor=NW)
# Charting screen Button
self.charting_screen_btn = Button(self.frame_menu_xtb_main_top, text='Main Screen')
self.charting_screen_btn.grid(row=0, column=0, padx=5, pady=5)
self.charting_screen_btn['font'] = menu_xtb_btn_font
# Symbol search button
self.symbol_search_btn = Button(self.frame_menu_xtb_main_top, text='Symbol Search', command=self.symbol_search_btn_xtb)
self.symbol_search_btn.grid(row=0, column=1, padx=5, pady=5)
self.symbol_search_btn['font'] = menu_xtb_btn_font
# Trading Bot Button
self.trading_bot_btn = Button(self.frame_menu_xtb_main_top, text='Trading Bot')
self.trading_bot_btn.grid(row=0, column=2, padx=5, pady=5)
self.trading_bot_btn['font'] = menu_xtb_btn_font
# Neural Nets Button
self.neural_nets_btn = Button(self.frame_menu_xtb_main_top, text='Neural Nets')
self.neural_nets_btn.grid(row=0, column=3, padx=5, pady=5)
self.neural_nets_btn['font'] = menu_xtb_btn_font
# Machine Learning Button
self.machine_learning_btn = Button(self.frame_menu_xtb_main_top, text='Machine Learning')
self.machine_learning_btn.grid(row=0, column=4, padx=5, pady=5)
self.machine_learning_btn['font'] = menu_xtb_btn_font
# main charting container
self.canvas_charting_xtb_main = Canvas(self.canvas_main, width=self.width_screen, height=(self.height_screen - canvas_top_height), bg='#ff9100')
self.canvas_charting_xtb_main.pack()
# position (0.0, -100) lowered by the height of frame_top_xtb_main height
self.canvas_charting_xtb_main.place(relx=0.0, y=canvas_top_height, anchor=NW)
# charting tools container
# contains tools to draw on chart
self.canvas_charting_tools = Canvas(self.canvas_charting_xtb_main, width=canvas_charting_tools_width, height=canvas_charting_tools_height, bg='#e80000')
self.canvas_charting_tools.pack()
# position (0.0, 0.0) relative to the frame_charting_xtb_main
self.canvas_charting_tools.place(relx=0.0, rely=0.0, anchor=NW)
# Secondary charting container
self.canvas_charting_xtb_sec = Canvas(self.canvas_charting_xtb_main, width=(self.width_screen - canvas_charting_tools_width), height=(self.height_screen - canvas_top_height), bg='#ff9100')
self.canvas_charting_xtb_sec.pack()
# position (0.0, -100) lowered by the height of frame_top_xtb_main height
self.canvas_charting_xtb_sec.place(x=canvas_charting_tools_width, y=0, anchor=NW)
# Paned Widow main
# Contains:
# Indicator panel
# Chart panel
# dowloades panel
# neural nets panel
self.paned_window_charting_main = PanedWindow(self.canvas_charting_xtb_sec, width=paned_window_charting_main_width, height=paned_window_charting_main_height, bg='#3700ff', orient=VERTICAL)
self.paned_window_charting_main.pack()
self.paned_window_charting_main.place(x=0, y=0)
# Canvas charting Bottom
# Contains:
# Available trained neural nets
self.canvas_charting_bottom = Canvas(width=canvas_charting_bottom_width, height=canvas_charting_bottom_height, bg='#000000')
self.canvas_charting_bottom.pack()
# Paned Window Charting Top
# Contains:
# Indicator panel
# Chart panel
# dowloads panel
self.paned_window_charting_top = PanedWindow(width=canvas_charting_top_width, height=canvas_charting_top_height, bg='#3700ff', orient=HORIZONTAL)
self.paned_window_charting_top.pack()
self.paned_window_charting_top.place(relx=0.0, rely=0.0, anchor=NW)
self.paned_window_charting_main.add(self.paned_window_charting_top)
self.paned_window_charting_main.add(self.canvas_charting_bottom)
# Canvas charting Indicators
# Contains:
# Indicators list available for chosen dataset
self.canvas_charting_indicators = Canvas(width=canvas_charting_indicators_width, height=canvas_charting_indicators_height)
self.canvas_charting_indicators.pack()
# Canvas charting chart
# Contains:
# Chart panel
self.canvas_charting_chart = Canvas(width=canvas_charting_chart_width, height=canvas_charting_chart_height)
self.canvas_charting_chart.pack()
# Paned Window Downloads And Sell/Buy Info
# Contains:
# Downloads Panel
# Symbol BUY/SELL Info
self.paned_window_charting_downloads_info = PanedWindow(width=paned_window_charting_downloads_info_width, height=paned_window_charting_downloads_info_height, orient=VERTICAL, bg='#3700ff')
self.paned_window_charting_downloads_info.pack()
# Canvas charting downloads
# Contains:
# Downloads panel
self.canvas_charting_downloads = Canvas(width=canvas_charting_downloads_width, height=canvas_charting_downloads_height)
self.canvas_charting_downloads.pack()
# Canvas charting info
# Contains:
# Symbol BUY/SELL Info
self.canvas_charting_info = Canvas(width=canvas_charting_info_width, height=canvas_charting_info_height)
self.canvas_charting_info.pack()
self.paned_window_charting_downloads_info.add(self.canvas_charting_downloads)
self.paned_window_charting_downloads_info.add(self.canvas_charting_info)
self.paned_window_charting_top.add(self.canvas_charting_indicators)
self.paned_window_charting_top.add(self.canvas_charting_chart)
self.paned_window_charting_top.add(self.paned_window_charting_downloads_info)
#self.getAllSymbols_xtb_api()
#resp = self.client.commandExecute(commandName='getSymbol', arguments=21)
#print(resp)
#price = self.getChartLastRequest(symbol_name=self.symbols_unique[0], period=5, time=1262944112000)
#print(price)
def login_tradingview_choose(self):
for widgets in self.canvas_main.winfo_children():
widgets.destroy()
self.login_tradingview_font = tkFont.Font(family='Calibri', size=25)
self.frame_tradingview_login = Frame(self.canvas_main)
self.frame_tradingview_login.pack()
self.frame_tradingview_login.place(relx=0.5, rely=0.5, anchor=CENTER)
self.tradingview_login_google_btn = tk.Button(self.frame_tradingview_login, text='Log in with Google', width=25, height=2, command=self.login_tradingview_google)
self.tradingview_login_google_btn.pack()
self.tradingview_login_google_btn['font'] = self.login_tradingview_font
self.tradingview_login_username_btn = tk.Button(self.frame_tradingview_login, text='log in with tradingview', width=25, height=2, command=self.login_tradingview_username)
self.tradingview_login_username_btn.pack()
self.tradingview_login_username_btn['font'] = self.login_tradingview_font
def login_tradingview_google(self):
for widgets in self.canvas_main.winfo_children():
widgets.destroy()
self.login_tradingview_google_font = tkFont.Font(family='Calibri', size=25)
self.tradingview_google_login = StringVar()
self.tradingview_google_login.set("Enter login or email here")
self.tradingview_google_password = StringVar()
self.tradingview_google_password.set("Enter password here")
self.frame_tradingview_google_login = Frame(self.canvas_main)
self.frame_tradingview_google_login.pack()
self.frame_tradingview_google_login.place(relx=0.5, rely=0.5, anchor=CENTER)
self.tradingview_google_login_entry = Entry(self.frame_tradingview_google_login, textvariable=self.tradingview_google_login, width=25)
self.tradingview_google_login_entry.pack()
self.tradingview_google_login_entry['font'] = self.login_tradingview_google_font
self.tradingview_google_password_entry = Entry(self.frame_tradingview_google_login, textvariable=self.tradingview_google_password, width=25)
self.tradingview_google_password_entry.pack()
self.tradingview_google_password_entry['font'] = self.login_tradingview_google_font
self.tradingview_google_log_in_btn = tk.Button(self.frame_tradingview_google_login, text='Log in')
self.tradingview_google_log_in_btn.pack()
self.tradingview_google_log_in_btn['font'] = self.login_tradingview_google_font
def login_tradingview_username(self):
for widgets in self.canvas_main.winfo_children():
widgets.destroy()
self.login_tradingview_username_font = tkFont.Font(family='Calibri', size=25)
self.tradingview_username_login = StringVar()
self.tradingview_username_login.set("Enter login or email here")
self.tradingview_username_password = StringVar()
self.tradingview_username_password.set("Enter password here")
self.frame_tradingview_username_login = Frame(self.canvas_main)
self.frame_tradingview_username_login.pack()
self.frame_tradingview_username_login.place(relx=0.5, rely=0.5, anchor=CENTER)
self.tradingview_username_login_entry = Entry(self.frame_tradingview_username_login, textvariable=self.tradingview_username_login, width=25)
self.tradingview_username_login_entry.pack()
self.tradingview_username_login_entry['font'] = self.login_tradingview_username_font
self.tradingview_username_password_entry = Entry(self.frame_tradingview_username_login, textvariable=self.tradingview_username_password, width=25)
self.tradingview_username_password_entry.pack()
self.tradingview_username_password_entry['font'] = self.login_tradingview_username_font
self.tradingview_username_log_in_btn = tk.Button(self.frame_tradingview_username_login, text='Log in')
self.tradingview_username_log_in_btn.pack()
self.tradingview_username_log_in_btn['font'] = self.login_tradingview_username_font
def log_in_xtb_api(self, userId, password):
# enter your login credentials here
userId = userId
password = "password"
# create & connect to RR socket
self.client = xAPIConnector.APIClient()
# connect to RR socket, login
loginResponse = self.client.execute(xAPIConnector.loginCommand(userId=userId, password=password))
xAPIConnector.logger.info(str(loginResponse))
# check if user logged in correctly
if (loginResponse['status'] == False):
print('Login failed. Error code: {0}'.format(loginResponse['errorCode']))
return
# get ssId from login response
ssid = loginResponse['streamSessionId']
self.runInParallel(self.xtb_main_screen, self.getAllSymbols_xtb_api)
def getAllSymbols_xtb_api(self):
symbols_init = self.client.commandExecute('getAllSymbols')
symbols_list_init = list(symbols_init.items())
symbols_list_final = list()
for i in range(len(symbols_list_init[1][1][:])):
symbols_list_final.append(symbols_list_init[1][1][i])
self.symbols_dataframe = pd.DataFrame(symbols_list_final)
self.unique_category = self.symbols_dataframe['categoryName'].unique()
self.unique_group = self.symbols_dataframe['groupName'].unique()
self.symbols_unique = self.symbols_dataframe['symbol'].unique()
print(self.unique_category)
print(self.unique_group)
def getChartLastRequest(self, symbol_name : str, period : int, time : int):
parameters = {"info" : {
"period": period,
"start": time,
"symbol": symbol_name
}}
price_init = self.client.commandExecute(commandName='getChartLastRequest', arguments=parameters)
print(price_init)
def symbol_search_btn_xtb(self):
for widgets in self.canvas_charting_xtb_sec.winfo_children():
widgets.place_forget()
self.symbol_search_xtb_ui()
def symbol_search_xtb_ui(self):
symbol_search_xtb_btn_font = tkFont.Font(family='Calibri', size=20)
self.frame_search_xtb_btns = Frame(self.canvas_charting_xtb_sec, width=(self.width_screen - math.floor(0.03 * self.width_screen)))
self.frame_search_xtb_btns.pack()
self.frame_search_xtb_btns.place(relx=0.0, rely=0.0, anchor=NW)
pixel = tk.PhotoImage(width=1, height=1)
self.label_search_xtb = Label(self.frame_search_xtb_btns, text='', image=pixel, width=(self.width_screen - math.floor(0.03 * self.width_screen)), anchor=W)
self.label_search_xtb.pack()
self.stocks_xtb_btn = Button(self.frame_search_xtb_btns, text='Stocks', anchor=W)
self.stocks_xtb_btn.pack(fill=X)
self.stocks_xtb_btn['font'] = symbol_search_xtb_btn_font
self.CRT_xtb_btn = Button(self.frame_search_xtb_btns, text='Stocks', anchor=W)
self.CRT_xtb_btn.pack(fill=X)
self.CRT_xtb_btn['font'] = symbol_search_xtb_btn_font
self.ETF_xtb_btn = Button(self.frame_search_xtb_btns, text='Stocks', anchor=W)
self.ETF_xtb_btn.pack(fill=X)
self.ETF_xtb_btn['font'] = symbol_search_xtb_btn_font
self.indexes_xtb_btn = Button(self.frame_search_xtb_btns, text='Indexes', anchor=W)
self.indexes_xtb_btn.pack(fill=X)
self.indexes_xtb_btn['font'] = symbol_search_xtb_btn_font
self.forex_xtb_btn = Button(self.frame_search_xtb_btns, text='Forex', anchor=W)
self.forex_xtb_btn.pack(fill=X)
self.forex_xtb_btn['font'] = symbol_search_xtb_btn_font
self.STK_xtb_btn = Button(self.frame_search_xtb_btns, text='Stocks', anchor=W)
self.STK_xtb_btn.pack(fill=X)
self.STK_xtb_btn['font'] = symbol_search_xtb_btn_font
self.CMD_xtb_btn = Button(self.frame_search_xtb_btns, text='Stocks', anchor=W)
self.CMD_xtb_btn.pack(fill=X)
self.CMD_xtb_btn['font'] = symbol_search_xtb_btn_font
def runInParallel(self, *fns):
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()
EDIT:
After deleting the last loop in runInParallel function the code looks like this:
def runInParallel(self, *fns):
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
p.join()
And I got an error after this error is raised new instance of the UI class opens up:
Traceback (most recent call last):
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\...\PycharmProjects\LSTM_multiple_indicators\UI.py", line 92, in xtb_log_in
self.log_in_xtb_api(userId=self.user_id_xtb, password=self.password_xtb)
File "C:\Users\...\PycharmProjects\LSTM_multiple_indicators\UI.py", line 358, in log_in_xtb_api
self.runInParallel(self.xtb_main_screen, self.getAllSymbols_xtb_api)
File "C:\Users\...\PycharmProjects\LSTM_multiple_indicators\UI.py", line 439, in runInParallel
p.start()
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 327, in _Popen
return Popen(process_obj)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
reduction.dump(process_obj, to_child)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
TypeError: cannot pickle '_tkinter.tkapp' object
You could define a function with the code you want to run and the UI_Main.after() method, for example something like this:
def runInParallel():
print('I am doing something.')
UI_Main.after(100, runInParallel)
UI_Main.after(100, runInParallel)
Something like this should work for you.
So I have this program which requests a file from the web and the user can download it. I am using urllib.request and tkinter for my program. The problem is that when the user hits the 'Download' button there is no pause or cancel until the file gets downloaded and the program freezes too. I really want to create a pause or a cancel button, but I do not know how and I want to eliminate the freezing of the program. Should I use another library like 'requests'? Or should I try threading? Can someone guide me through this?
My code(BTW if you know any way to improve my program I would appreciate it a lot if you shared it with me):
from tkinter import *
from tkinter import font as tkFont
import random
import urllib.request
import requests
from tqdm import tqdm
from tqdm.auto import tqdm
def printsth():
print("Yay it works! ")
def main_menu():
root = Tk()
# the top menu
num = IntVar()
# var = IntVar()
menu = Menu(root)
root.config(menu=menu)
submenu = Menu(menu)
menu.add_cascade(label="Settings", menu=submenu)
def custom_op():
custom = Tk()
custom.mainloop()
submenu.add_command(label="Customization ", command=custom_op)
def settings_op():
set_win = Tk()
set_win.mainloop()
submenu.add_command(label="Settings ", command=settings_op)
submenu.add_separator()
submenu.add_command(label="Exit", command=root.destroy)
# the edit menu
editmenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editmenu)
editmenu.add_command(label="Redo...", command=printsth)
# the tool bar
toolbar = Frame(root, bg="light gray")
insert_button = Button(toolbar, text="Insert an image", command=printsth)
insert_button.pack(side=LEFT, padx=2, pady=2)
print_button = Button(toolbar, text="Print", command=printsth)
print_button.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
# the download function
def download_image():
global formatname
if num.get() == 1:
name = random.randrange(1, 100000)
else:
name = str(name_entry.get())
formatname = str(format_entry.get())
'''if var.get() == 1:
operator = str(url_entry.get())
formatname = '.' + operator[-3] + operator[-2] + operator[-1]
else:
pass'''
fullname = str(name) + formatname
url = str(url_entry.get())
fw = open('file-size.txt', 'w')
file_size = int(requests.head(url, headers={'accept-encoding': ''}).headers['Content-Length'])
fw.write(str(file_size))
fw.close()
path = str(output_entry.get()) + "\\"
urllib.request.urlretrieve(url, path.replace("\\", "\\\\") + fullname)
# the status bar
status_bar = Label(root, text="Downloading...", bd=1, relief=SUNKEN, anchor=W)
status_bar.pack(side=BOTTOM, fill=X)
# the download frame
body_frame = Frame(root, bg="light blue")
download_button = Button(body_frame, text="Download! ", command=download_image, border=3, width=20, height=5)
download_design = tkFont.Font(size=12, slant='italic')
download_button['font'] = download_design
download_button.pack(side=LEFT, pady=5, padx=5)
body_frame.pack(side=LEFT, fill=Y)
# the main interaction menu
inter_frame = Frame(root)
url_entry = Entry(inter_frame)
label = Label(inter_frame, text="Enter the image URL: ")
file_format = Label(inter_frame, text="Choose your file format: ")
format_entry = Entry(inter_frame)
file_name = Label(inter_frame, text="File's name: ")
name_entry = Entry(inter_frame)
check_name = Checkbutton(inter_frame, text="Give a random name", variable=num)
# check_format = Checkbutton(inter_frame, text="Download with default format", variable=var)
output_path = Label(inter_frame, text="Choose output path: ")
output_entry = Entry(inter_frame)
file_name.pack(anchor=CENTER, expand=1)
name_entry.pack(anchor=CENTER, expand=1)
check_name.pack(anchor=CENTER, expand=1)
label.pack(anchor=CENTER, expand=1)
url_entry.pack(anchor=CENTER, expand=1)
file_format.pack(anchor=CENTER, expand=1)
format_entry.pack(anchor=CENTER, expand=1)
# check_format.pack(anchor=CENTER)
output_path.pack(anchor=CENTER, expand=1)
output_entry.pack(anchor=CENTER, expand=1)
inter_frame.pack(expand=1)
root.mainloop()
# the end!
main_menu()
You can use reporthook option of urllib.request.urlretrieve() to associate a callback and abort the download by raising exception inside the callback:
downloading = False # flag to indicate whether download is active
def download_progress(count, blksize, filesize):
nonlocal downloading
if downloading:
downloaded = count * blksize
print('downloaded %s / %s' % (downloaded, filesize))
root.update() # let user interact with the GUI
else:
# user selects to abort the download
raise Exception('download aborted!')
# the download function
def download_image():
global formatname
nonlocal downloading
if downloading:
downloading = False
return
download_button.config(text='Stop!') # let user to click the button to abort download
downloading = True
if num.get() == 1:
name = random.randrange(1, 100000)
else:
name = str(name_entry.get())
formatname = str(format_entry.get())
'''if var.get() == 1:
operator = str(url_entry.get())
formatname = '.' + operator[-3] + operator[-2] + operator[-1]
else:
pass'''
fullname = str(name) + formatname
url = str(url_entry.get())
fw = open('file-size.txt', 'w')
file_size = int(requests.head(url, headers={'accept-encoding': ''}).headers['Content-Length'])
fw.write(str(file_size))
fw.close()
path = str(output_entry.get()) + "\\"
try:
urllib.request.urlretrieve(url, path.replace("\\", "\\\\")+fullname, download_progress) # added reporthook callback
except Exception as e:
print(e) # download aborted
else:
print('done')
download_button.config(text='Download!') # resume download button
The text of download_button is changed to Stop! after it is clicked so that user can click it again to abort the download. When the download is aborted/completed, its text is changed back to "Download!".
I am currently making a GUI with Tkinter that plays music. The program is able to correctly play the songs, and I am trying to implement a pause button. This is the code I have, does anyone know why this might not be working? I know the button is linked properly since I have tried printing something out when the button is clicked, and that works. Also, there are no error messages, the audio is just not pausing.
import pygame
from tkinter import *
import os
import urllib.request
import urllib.parse
import re
import requests
from PIL import ImageTk, Image
class Application(Frame):
def __init__(self, master):
super().__init__(master)
self.grid()
pygame.mixer.init()
self.downloadNum = 1
self.pack(fill = BOTH, expand = 1)
self.songDict = {}
num = 1
while True:
if os.path.exists(str(num)+'.jpg'):
os.remove(str(num)+'.jpg')
num += 1
else:
break
self.create_widgets()
def create_widgets(self):
Label(self, text="Available Songs").grid(row=0, column=0)
for filename in os.listdir(r'C:\Users\alvin\Documents\School'):
if filename.endswith(".mp3"):
string = ""
for x in filename:
if x == "_":
string += " "
else:
if x == ".":
break
string += x
Label(self, text=string).grid()
Label(self, text = "Enter your song!").grid(row=0, column = 1)
self.entryBox = Entry(self)
self.entryBox.grid(row=1, column =1)
Button(self, text="Play!", command = self.playSong).grid(row=2, column =1)
Label(self).grid(row=3, column =1)
Label(self, text="Currently Playing:").grid(row=4, column=1)
self.playing = Label(self, text="")
self.playing.grid(row=5, column=1)
def playSong(self):
self.song = self.entryBox.get()
self.newsong = ""
for x in self.song:
if x == " ":
self.newsong += "_"
else:
self.newsong += x
self.newsong = self.newsong.title()
self.newsong = self.newsong + ".mp3"
pygame.mixer.music.load(self.newsong)
pygame.mixer.music.play(0)
self.playing.configure(text=self.song.title())
query_string = urllib.parse.urlencode({"search_query": self.song.title()})
html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
f = open(str(self.downloadNum) +'.jpg','wb')
f.write(requests.get('https://img.youtube.com/vi/' + search_results[0] + '/default.jpg').content)
f.close()
self.songDict[self.downloadNum] = self.newsong
load = Image.open(str(self.downloadNum) + ".jpg")
render = ImageTk.PhotoImage(load)
img = Label(self, image=render)
img.image = render
img.place(x=145, y=135)
self.downloadNum += 1
Label(self).grid(row=6, column =0)
Label(self).grid(row=7, column=0)
Label(self).grid(row=8, column=0)
Label(self).grid(row=9, column=0)
Label(self).grid(row=10, column=0)
pauseButton = Button(self, text="||", command = self.pause)
pauseButton.grid(row = 11, column = 1)
def pause(self):
pygame.mixer.pause()
root = Tk()
root.title("MP3 Player")
root.geometry("400x400")
app = Application(root)
root.mainloop()
try using:
pygame.mixer.music.pause()
instead of:
pygame.mixer.pause()
i have a problem with the user-output of my tkinter gui.
First of all it works, but there is a huge problem with the import to a new py file. It throws a Error ().
Traceback (most recent call last):
File "F:\Python_Projekt\Übung\Plus\test.py", line 4, in <module>
tk = own.get_start()
File "F:\Python_Projekt\Übung\Plus\plus_window_pack2.py", line 31, in get_start
sel = ListBox1.curselection()
File "C:\Users\nox\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 2782, in curselection
return self._getints(self.tk.call(self._w, 'curselection')) or ()
_tkinter.TclError: invalid command name ".!frame.!frame.!listbox"
I know there is a problem with my ListBox but i have no clue how to handle it. I need the used output for my new script. So i could work with it.
from tkinter import*
import tkinter as tk
window = Tk()
rahmen1 = Frame(master = window) #, bg='black'
rahmen1.pack(side='top', padx=5, pady=5)
rahmen2 = Frame(master = rahmen1) #, bg= 'yellow'
rahmen2.pack(side='left', padx=5, pady=5)
def get_start():
selection=ListBox1.curselection()
picked = selection[0]
used = ListBox1.get(picked) #-------user-input
print(used)
return used
####################----------------------------------------------------
List = ['Dax','Dow','EUR/USD', 'Gold', 'Silber','EUR/JPY','USD/JPY']
scrollbar1 = Scrollbar(rahmen2) # ,bg='green'
scrollbar1.pack(padx = 1,side = 'right',fill=Y)
ListBox1 = Listbox(rahmen2,exportselection = False)
ListBox1.config( yscrollcommand = scrollbar1.set, width = 40)
scrollbar1.config( command = ListBox1.yview) # ,bg='blue'
for i in List:
ListBox1.insert(tk.END, str(i))
ListBox1.pack(padx = 1,)
###################------------------------------------------------
Button1 = Button(rahmen2,text='Get Data', font = 'bold')
Button1.config (width=40, height = 3, command = get_start)
Button1.pack( )
window.mainloop()
I changed the code to get the important part. For a better understanding of my problem.
if i want to get the user-input it thorw's me the error.
Try this. I have added a simple check to make sure something's selected (I'm not sure what the error at the top of your question's about though):
def get_start():
selection=ListBox1.curselection()
if len (selection) != 0:
picked = selection[0]
used = ListBox1.get(picked) #-------user-input
print(used)
return used
EDIT:
This checks every x seconds (defined by UPDATE_TIME) for checkbox updates
UPDATE_TIME = 0.1
from tkinter import*
import tkinter as tk
import threading, time
window = Tk()
rahmen1 = Frame(master = window) #, bg='black'
rahmen1.pack(side='top', padx=5, pady=5)
rahmen2 = Frame(master = rahmen1) #, bg= 'yellow'
rahmen2.pack(side='left', padx=5, pady=5)
def get_start():
print (previous)
return previous
def get_update ():
global previous
try:
while True:
selection=ListBox1.curselection()
if len (selection) == 0: previous = None
else:
picked = selection[0]
previous = ListBox1.get(picked) #-------user-input
time.sleep (UPDATE_TIME)
except: pass
####################----------------------------------------------------
List = ['Dax','Dow','EUR/USD', 'Gold', 'Silber','EUR/JPY','USD/JPY']
scrollbar1 = Scrollbar(rahmen2) # ,bg='green'
scrollbar1.pack(padx = 1,side = 'right',fill=Y)
ListBox1 = Listbox(rahmen2,exportselection = False)
ListBox1.config( yscrollcommand = scrollbar1.set, width = 40)
scrollbar1.config( command = ListBox1.yview) # ,bg='blue'
for i in List:
ListBox1.insert(tk.END, str(i))
ListBox1.pack(padx = 1,)
###################------------------------------------------------
Button1 = Button(rahmen2,text='Get Data', font = 'bold')
Button1.config (width=40, height = 3, command = get_start)
Button1.pack ()
threading.Thread (target = get_update).start ()
window.mainloop()