How can I access Tkinter widgets outside of the init scope - python

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

Related

Python GUI App is not functioning well, help me fix it?

Here's my code of a gui app using tkinter library, it creats tables and prints orders for each table and gives the ability to edit orders on every table. the goal of it to know what did each table order. but editing the orders doesn't seem to work at all, I need help fixing it.
import tkinter as tk
class TableOrdersApp:
def __init__(self, master):
self.tables = []
self.table_list = tk.Listbox(master)
self.table_list.pack(side=tk.LEFT, fill=tk.BOTH)
self.table_list.bind("<<ListboxSelect>>", self.refresh_label)
self.orders_label = tk.Label(master, text="", anchor=tk.W, justify=tk.LEFT, wraplength=400)
self.orders_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(master)
self.button_frame.pack(side=tk.RIGHT)
self.add_button = tk.Button(self.button_frame, text="Add Table", command=self.add_table)
self.add_button.pack(side=tk.TOP)
self.remove_button = tk.Button(self.button_frame, text="Remove Table", command=self.remove_table)
self.remove_button.pack(side=tk.TOP)
self.edit_button = tk.Button(self.button_frame, text="Edit Order", command=self.edit_order)
self.edit_button.pack(side=tk.TOP)
self.remove_order_button = tk.Button(self.button_frame, text="Remove Order", command=self.remove_order)
self.remove_order_button.pack(side=tk.TOP)
def add_table(self):
self.tables.append([])
self.table_list.insert(tk.END, "Table {}".format(len(self.tables)))
def remove_table(self):
index = self.table_list.curselection()[0]
self.tables.pop(index)
self.table_list.delete(index)
def refresh_label(self, event=None):
self.orders_label.config(text="\n".join(self.tables[self.table_list.curselection()[0]]))
def edit_order(self):
index = self.table_list.curselection()[0]
orders = self.tables[index]
if self.orders_label.select_present():
start_index = self.orders_label.index(tk.SEL_FIRST)
end_index = self.orders_label.index(tk.SEL_LAST)
selected_text = self.orders_label.selection_get()
num_newlines = selected_text.count("\n")
order_index = start_index.split(".")[0] - 1 - num_newlines
new_order = tk.simpledialog.askstring("Edit Order", "Enter the new order:")
orders[order_index] = new_order
self.refresh_label()
def remove_order(self):
index = self.table_list.curselection()[0]
orders = self.tables[index]
start_index = self.orders_label.index(tk.SEL_FIRST)
end_index = self.orders_label.index(tk.SEL_LAST)
num_newlines = self.orders_label.get(start_index, end_index).count("\n")
order_index = start_index.split(".")[0] - 1 - num_newlines
orders.pop(order_index)
self.refresh_label()
# Create the main window
root = tk.Tk()
# Create an instance of the TableOrdersApp class
app = TableOrdersApp(root)
# Run the main loop of the app
root.mainloop()
I tried to make it print a label and make it editable using "edit order" button, but the button itself doesn't seem to work, and I want it to print "Empty" if the table has no orders how can i do that.
Look in edit_order and remove_order function. Must easier to write less coding.
Here is code:
import tkinter as tk
class TableOrdersApp:
def __init__(self, master):
self.tables = []
self.table_list = tk.Listbox(master)
self.table_list.pack(side=tk.LEFT, fill=tk.BOTH)
self.table_list.bind("<<ListboxSelect>>", self.refresh_label)
self.orders_label = tk.Label(master, text="", anchor=tk.W, justify=tk.LEFT, wraplength=400)
self.orders_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(master)
self.button_frame.pack(side=tk.RIGHT)
self.add_button = tk.Button(self.button_frame, text="Add Table", command=self.add_table)
self.add_button.pack(side=tk.TOP)
self.remove_button = tk.Button(self.button_frame, text="Remove Table", command=self.remove_table)
self.remove_button.pack(side=tk.TOP)
self.edit_button = tk.Button(self.button_frame, text="Edit Order", command=self.edit_order)
self.edit_button.pack(side=tk.TOP)
self.remove_order_button = tk.Button(self.button_frame, text="Remove Order", command=self.remove_order)
self.remove_order_button.pack(side=tk.TOP)
def add_table(self):
self.tables.append([])
self.table_list.insert(tk.END, "Table {}".format(len(self.tables)))
def remove_table(self):
index = self.table_list.curselection()[0]
self.tables.pop(index)
self.table_list.delete(index)
def refresh_label(self, event=None):
self.orders_label.config(text="\n".join(self.tables[self.table_list.curselection()[0]]))
def edit_order(self):
index = self.table_list.curselection()[0]
orders = self.table_list.get(index)
print(index)
order = orders
self.orders_label.configure(text=order)
#if self.orders_label.select_present():
#start_index = self.orders_label.index(tk.SEL_FIRST)
#end_index = self.orders_label.index(tk.SEL_LAST)
#selected_text = self.orders_label.selection_get()
#num_newlines = selected_text.count("\n")
#order_index = start_index.split(".")[0] - 1 - num_newlines
#new_order = tk.simpledialog.askstring("Edit Order", "Enter the new order:")
#orders[order_index] = new_order
#self.refresh_label()
def remove_order(self):
remove_orders = self.table_list.curselection()
self.table_list.delete(remove_orders)
self.orders_label.configure(text="")
#index = self.table_list.curselection()[0]
#orders = self.tables[index]
#start_index = self.orders_label.index(tk.SEL_FIRST)
#end_index = self.orders_label.index(tk.SEL_LAST)
#num_newlines = self.orders_label.get(start_index, end_index).count("\n")
#order_index = start_index.split(".")[0] - 1 - num_newlines
#orders.pop(order_index)
#self.refresh_label()
# Create the main window
root = tk.Tk()
# Create an instance of the TableOrdersApp class
app = TableOrdersApp(root)
# Run the main loop of the app
root.mainloop()
Result when executes:
Result when selected:
Result when removed order:

I am writning a UI class I need some functions to run in the background while UI is working

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.

How to make find and replace system in python

This a simple code in which i have created a text area using tkinter and a menu in which there is a option of find and replace in which if user click on it then a gui will appear in which user will enter a word to whom they want to replace and then a word to whom they want replace with but till now i have just created a gui . But how can i replace word with a word given by user with the text of text area that i have created.
from tkinter import *
import tkinter.font as font
from tkinter import messagebox
root = Tk()
root.title("MyCodeEditor")
editor = Text()
editor.pack()
menu_bar = Menu(root)
def find_replace():
f = Tk()
f.title("Find and Replace")
find_label = Label(f,text = "Find : ")
replace_label = Label(f,text = "Replace : ")
find_label.grid(row = 0 , column = 0)
replace_label.grid(row = 3 , column = 0)
global find_enter
global replace_enter
find_enter = Entry(f,fg = "black" , background = "blue",borderwidth = 5,width = 40)
replace_enter = Entry(f,fg = "black" , background = "blue", borderwidth = 5, width =40 )
find_enter.grid(row = 0 , column = 1)
replace_enter.grid(row = 3 , column = 1)
btn_replace = Button(f,text = 'Replace',fg = 'black',command = None)
btn_replace.grid(row=0, column = 5)
format_bar = Menu(menu_bar , tearoff = 0)
format_bar.add_command(label = 'Find and Replace',command = find_replace)
menu_bar.add_cascade(label = 'Format' ,menu = format_bar )
root.config(menu = menu_bar)
root.mainloop()
Here is a simple example (most of it is just the GUI looks, the main part is the actual replace method):
from tkinter import Tk, Text, Entry, Frame, Button, Toplevel, Label, Menu, TclError, IntVar
normal_font = ('comicsans', 10)
class FindAndReplace(Toplevel):
def __init__(self, parent, text_widget: Text):
Toplevel.__init__(self, parent)
self.focus_force()
self.title('Find and Replace')
self.geometry('500x200')
self.resizable(False, False)
self.parent = parent
self.widget = text_widget
try:
self.start_index = self.widget.index('sel.first')
self.end_index = self.widget.index('sel.last')
except TclError:
self.start_index = '1.0'
self.end_index = 'end'
self.to_find = None
self.to_replace = None
# creating find entry
find_frame = Frame(self)
find_frame.pack(expand=True, fill='both', padx=20)
Label(find_frame, text='Find:', font=normal_font).pack(side='left', fill='both', padx=20)
self.find_entry = Entry(find_frame)
self.find_entry.pack(side='right', expand=True, fill='x')
# creating replace entry
replace_frame = Frame(self)
replace_frame.pack(expand=True, fill='both', padx=20)
Label(replace_frame, text='Replace:', font=normal_font).pack(side='left', fill='both', padx=20)
self.replace_entry = Entry(replace_frame)
self.replace_entry.pack(side='right', expand=True, fill='x')
# creating buttons
button_frame = Frame(self)
button_frame.pack(expand=True, fill='both', padx=20)
Button(button_frame, text='Cancel', font=normal_font,
command=self.destroy).pack(side='right', fill='x', padx=5)
Button(button_frame, text='Replace', font=normal_font,
command=self.replace).pack(side='right', fill='x', padx=5)
def __find_get(self):
self.to_find = self.find_entry.get()
def __replace_get(self):
self.to_replace = self.replace_entry.get()
def replace(self):
self.__find_get()
self.__replace_get()
if not self.to_replace:
return
length = IntVar()
index = self.widget.search(self.to_find, self.start_index, stopindex=self.end_index, count=length)
end_index = self.widget.index(index + f'+{length.get()}c')
self.widget.delete(index, end_index)
self.widget.insert(index, self.to_replace)
root = Tk()
menu_bar = Menu(root)
file_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='Find and Replace', command=lambda: FindAndReplace(root, text))
root.config(menu=menu_bar)
text = Text(root)
text.pack()
root.mainloop()
Obviously some other functionality could be added such as replace all

having trouble in setting up a calendar in tkinter

i have a small ui programm and i need to display a calendar in it or a date picker . (NOTE : userid and password is root")**
i have tried this code :
from Tkinter import *
from PIL import Image, ImageTk
import ttkcalendar
class App():
def __init__(self):
pass
root = Tk()
root.configure(bg='black')
root.attributes('-alpha', 0.0)
def mainWindow(self):
self.root.geometry('{}x{}'.format(600,400))
self.root.attributes('-alpha', 1)
self.root.configure(bg='#404040')
self.ttkcal = ttkcalendar.Calendar(self.root,firstweekday=calendar.SUNDAY)
self.ttkcal.pack()
self.root.wm_title("time sheet management system")
# Create the toolbar as a frame
self.toolbar = Frame(self.root, borderwidth=1, relief='raised')
self.toolbar.configure( bg = '#838383')
# Load all the images first as PNGs and use ImageTk to convert
# them to usable Tkinter images.
self.img1 = Image.open('NewIcon.png')
self.useImg1 = ImageTk.PhotoImage(self.img1)
self.img2 = Image.open('LoadIcon.png')
self.useImg2 = ImageTk.PhotoImage(self.img2)
self.img3 = Image.open('SaveIcon.png')
self.useImg3 = ImageTk.PhotoImage(self.img3)
# Set up all the buttons for use on the toolbars.
newBtn = Button(self.toolbar, image=self.useImg1, command=self.callback)
newBtn.pack(side=LEFT, fill=X)
loadBtn = Button(self.toolbar, image=self.useImg2, command=self.callback)
loadBtn.pack(side=LEFT, fill=X)
saveBtn = Button(self.toolbar, image=self.useImg3, command=self.callback)
saveBtn.pack(side=LEFT, fill=X)
# Add the toolbar
self.toolbar.pack(side=TOP, fill=X)
"""
#create a frame
self.infoArea= Frame(self.root, borderwidth=2,height=40,width=100, relief='raised',bg='red')"""
self.root.mainloop()
"""
# Set up a Text box and scroll bar.
self.scrollbar = Scrollbar(self.root)
self.scrollbar.pack(side=RIGHT, fill=Y)
self.text = Text(self.root)
self.text.pack()
self.text.config(yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.text.yview)"""
def loginClick(self):
self.userid = self.txt1.get()
self.password = self.txt2.get()
print self.userid,self.password
if self.password == 'root' and self.userid == 'root':
self.wi.destroy()
self.mainWindow()
def callback(self):
print "A button was pressed"
def login(self):
self.wi = Toplevel (self.root)
#self.wi.geometry('{}x{}'.format(200,200))
self.wi.configure(bg='#404040')
self.wi.overrideredirect(1)
self.wi.update_idletasks()
self.w = self.wi.winfo_screenwidth()
self.h = self.wi.winfo_screenheight()
self.size = tuple(int(_) for _ in self.wi.geometry().split('+')[0].split('x'))
self.x = self.w/2 - self.size[0]/2
self.y = self.h/2 - self.size[1]/2
self.wi.geometry("%dx%d+%d+%d" % (self.size + (self.x, self.y)))
self.wi.geometry('{}x{}'.format(400,200))
self.frame1 = Frame ( self.wi,bg='#404040' )
self.frame1.pack(side=BOTTOM,fill=X)
self.butt1 = Button(self.frame1,text= "Cancel" , bg = '#838383',fg='white',command = self.wi.destroy)
self.butt1.pack(side=RIGHT,padx=1)
self.butt2 = Button(self.frame1,text= "Login" ,bg = '#838383',fg='white',command = self.loginClick)
self.butt2.pack(side=RIGHT)
"""self.frame2 = Frame ( self.wi,bg='green' )
self.frame2.pack(side=BOTTOM,fill=BOTH)"""
self.lab1 = Label (self.wi,text='UserID',bg='#404040',fg='white')
#self.lab1.pack(side=LEFT,padx=60,pady=20)
self.lab1.place(x=60,y=20)
self.lab2 = Label (self.wi,text='Password',bg='#404040',fg='white')
#self.lab1.pack(side=LEFT,padx=60,pady=20)
self.lab2.place(x=60,y=60)
self.txt1 = Entry( self.wi)
self.txt1.place(x=140,y=20)
self.txt2 = Entry( self.wi,show='*')
self.txt2.place(x=140,y=60)
"""
self.label = Label(self.wi,text="UserID",bg='#838383',fg='white')
self.label.place("""
self.wi.mainloop()
if __name__ == "__main__":
a = App()
#a.root.mainloop()
a.login()
but it is giving error that "name calendar not defined". how can i solve this ?
or is there any other way to implement a calendar or date picker in tkinter.
The code is using calendar module, but it is not importing the module.
self.ttkcal = ttkcalendar.Calendar(self.root, firstweekday=calendar.SUNDAY)
^^^^^^^^^^^^^^^
Simply adding following import statement will solve the problem.
import calendar

trouble figuring out how to open a new window in tkinter "attribute error"

I am a beginner programmer and want to open a new window after a bottom in clicked in tkinter. I looked online and tried some things but I don't really understand it and keep getting errors. Here is the error I get now.
File "C:\Python33\lib\tkinter\__init__.py", line 2046, in _setup
self.tk = master.tk
AttributeError: 'App' object has no attribute 'tk'
Here is my code
from tkinter import *
import random
player_dice = []
class App:
def __init__(self, master):
for i in range(1,6):
x = random.randint(1,6)
player_dice.append(x)
self.label = Label(master, text = x , fg = "red").grid(row =0, column =i+1)
self.label = Label(master, text = "Dice:" , fg = "red").grid(row =0, column =1)
self.hi_one = Button(master, text="one", command=self.say_one).grid(row = 1, column = 1)
def say_one(self):
print ("1")
window = Toplevel(self)
self.label = Label(window, text = "you selected one" , fg = "red").grid(row =3, column =3)
root = Tk()
app = App(root)
root.mainloop()
thanks for your help
Pass root, not self when call Toplevel: Toplevel(root). Or omit argument: Toplevel()
from tkinter import *
import random
player_dice = []
class App:
def __init__(self, master):
for i in range(1,6):
x = random.randint(1,6)
player_dice.append(x)
self.label = Label(master, text = x , fg = "red").grid(row =0, column =i+1)
self.label = Label(master, text = "Dice:" , fg = "red").grid(row =0, column =1)
self.hi_one = Button(master, text="one", command=self.say_one).grid(row = 1, column = 1)
def say_one(self):
print ("1")
window = Toplevel(root) # self -> root
self.label = Label(window, text = "you selected one" , fg = "red").grid(row =3, column =3)
root = Tk()
app = App(root)
root.mainloop()

Categories