Animated background using two images in Tkinter - python

I would like to continuously switch between two images after some interval lets say(200 ms) to get a animated flashing/blinking like appearance in the background. I have only managed to get still image for now.
This following code is the child window of a main program which is calling the function Refresher.
Main function:
def rad_alarm(self):
self.alarm = Tk.Toplevel()
self.alarm.geometry('1024x600')
#self.alarm.title("Alert")
vFont = tkFont.Font(family = 'Helvetica', size = 30)
#self.center(self.alarm)
self.alarm.overrideredirect(1)
#self.alarm.wm_attributes('-type', 'splash');
radfilename = PhotoImage(file = "radio1.png")
self.alarm.background_label = Label(self.alarm, image=radfilename)
self.alarm.background_label.pack()
bcklbl = Label(self.alarm, text = str(bck), bg="black", fg="Yellow", font=vFont)
bcklbl.place(x = 825, y = 300, width=140, height=40)
cpslbl = Label(self.alarm, text = str(counti), bg="black", fg="Yellow", font=vFont)
cpslbl.place(x = 825, y = 445, width=140, height=40)
dtlbl = Label(self.alarm, text = datetime.now().strftime('%Y-%m-%d %H:%M:%S'), bg="black", fg="Yellow", font=vFont)
dtlbl.place(x = 630, y = 140, width=380, height=40)
button=Button(self.alarm, text="Acknowledge Alarm", command=self.alarm_close, relief=FLAT, bg="black", fg="Red", font=vFont)
button.place(x = 400, y = 510, width=380, height=80)
dt=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
self.conn.execute("INSERT INTO ALARMS (CPS,BCK,DT) VALUES (?,?,?)",(counti, bck, dt));
self.conn.commit()
self.Refresher()
Function called for animation:
def Refresher(self):
sleep(0.1)
radfilename = PhotoImage(file = "radio2.png")
self.alarm.background_label.configure(image=radfilename)
sleep(0.1)
radfilename = PhotoImage(file = "radio1.png")
self.alarm.background_label.configure(image=radfilename)
self.alarm.background_label.after(200, self.Refresher)
As I said I am only getting a still image on background instead of flashing/blinking animation. Any idea where I am going wrong ?

Related

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.

Problem when export csv using Pandas (file cannot read chinese char)

I am trying to create flashcard game, but I have problem when trying to export dict to csv using pandas.
My dictionary has contained some Chinese letters and pinyin.
When I have played with multiple encodings, seem sometime Chinese letter can be read but pinyin is unreadable, sometimes its vice versa.
I'm not sure what is the issue about my code. please help me.
Thank you very much
Remark
for pinyin Im using slash or back-slash or dash to indicate tone
Ex. bàn tiān,
when import to csv, the program still can read those tone symbol, but not when export.
Example
export csv is on line 109-110
import random
import pandas as pd
from tkinter import *
from PIL import Image, ImageTk
windows = Tk()
windows.geometry(r"300x360")
windows.config(bg='#f7f5dd')
my_pic = Image.open(r"C:\\Users\\xx\\PycharmProjects\\flashcard\\Picture1.png")
scale_factor = 0.3
resized = my_pic.resize((int(712 * scale_factor), int(667 * scale_factor)))
img = ImageTk.PhotoImage(resized)
canvas = Canvas(width=235, height=235, bg="#f7f5dd", highlightthickness=0)
canvas.create_image(120, 120, image=img)
canvas.grid(column=1, row=1, pady=20, padx=30, columnspan=3)
know_button = Button()
dont_know_button = Button()
already_know_list = []
pix1 = Image.open(r"C:\Users\xx\PycharmProjects\flashcard\correct.png")
pix2 = Image.open(r"C:\Users\xx\PycharmProjects\flashcard\wrong.png")
scale_factor2 = 0.15
resized1 = pix1.resize((int(274 * scale_factor2), int(275 * scale_factor2)))
resized2 = pix2.resize((int(274 * scale_factor2), int(275 * scale_factor2)))
img1 = ImageTk.PhotoImage(resized1)
img2 = ImageTk.PhotoImage(resized2)
know_button.config(image=img1, bg="#f7f5dd", highlightthickness=0)
dont_know_button.config(image=img2, bg="#f7f5dd", highlightthickness=0)
know_button.grid(column=0, row=2, columnspan=2)
dont_know_button.grid(column=3, row=2, columnspan=2)
data = pd.read_csv(r"C:\\Users\\xx\\PycharmProjects\\flashcard\\hsk_vocabs_1_5.csv")
custom_data = data
number = random.randint(0, len(data))
chn_obj = canvas.create_text(120, 140, text=f"{data['Chinese'][number]}\n{data['Pinyin'][number]}", fill="white",
font=('Dosis SemiBold', 20, 'bold'), anchor='center')
five_sec_label = Label()
five_sec_label.config(text="3", font=('Dosis SemiBold', 20, 'bold'), bg="#f7f5dd")
five_sec_label.grid(column=1, row=2, columnspan=3)
init_sec = 3
timer = None
def clock(total_second):
global chn_obj, timer, init_sec
if total_second >= 0:
timer = windows.after(1000, clock, total_second - 1)
five_sec_label.config(text=f"{total_second}", font=('Corrier', 20, 'bold'))
else:
canvas.itemconfig(chn_obj, text="")
chn_obj = canvas.create_text(120, 140, text=f"{data['English'][number]}", fill="black",
font=('Dosis SemiBold', 15, 'bold'), anchor='center')
init_sec = 0
def next_word():
global number, chn_obj, timer, init_sec
init_sec = 3
canvas.itemconfig(chn_obj, text="")
chn_obj = canvas.create_text(120, 140, text=f"{data['Chinese'][number]}\n{data['Pinyin'][number]}", fill="white",
font=('Dosis SemiBold', 20, 'bold'), anchor='center')
windows.after_cancel(timer)
five_sec_label.config(text="")
clock(init_sec)
unknown_word = []
def already_know():
global already_know_list, number
already_know_list.append(number)
while number in already_know_list:
number = random.randint(0, len(data))
next_word()
def append_unknown_words():
global number, init_sec
if init_sec != 0:
return
else:
unknown_word.append(data['Chinese'][number])
number = random.randint(0, len(data))
next_word()
chinese_list = []
pinyin_list = []
english_list = []
def export_when_finished():
global unknown_word, chinese_list, pinyin_list, english_list
unknown_file = {
"Chinese": chinese_list,
"Pinyin": pinyin_list,
"English": english_list
}
for item in unknown_word:
chinese_list.append(data[data["Chinese"] == item]["Chinese"].values[0])
pinyin_list.append(data[data["Chinese"] == item]["Pinyin"].values[0])
english_list.append(data[data["Chinese"] == item]["English"].values[0])
df = pd.DataFrame(unknown_file)
df.to_csv('Unknown_Words.csv', encoding="utf-8")
exit()
know_button.config(command=already_know)
dont_know_button.config(command=append_unknown_words)
stop_game_n_export = Button()
stop_game_n_export.config(text="Stop and Export Unknown Words", font=('Dosis SemiBold', 10, 'bold'),
command=export_when_finished)
stop_game_n_export.grid(column=0, row=0, columnspan=3, rowspan=1)
clock(init_sec)
windows.mainloop()

Change the distance of radiobutton Tkinter

I am using tkinter for this project. After inputting the radiobuttons, I realize the distance from the box to the icon is different between two radiobuttons.I also try set the same size but it still unchanges.Can anyone help me?
s_img = PhotoImage(file = 'fullscreen4.png')
img_label = Label(image = fulls_img)
fulls_btn = Radiobutton(root,image = fulls_img, text="Full Screen", variable=var, value=1,borderwidth =0,bg = '#c3d3f0').place(x = 610, y = 90 )
areas_img = PhotoImage(file = 'area1.png')
img1_label = Label(image = areas_img)
area_btn = Radiobutton(root,image = areas_img, text="Area", variable=var, value=2,borderwidth =0,bg = '#c3d3f0').place(x = 610, y = 150 )

trying to have the same label entry as the first frame to the second frame. Tkinter

trying to have the same label entry as the first frame to the second frame. have tried to add the second label to my function, however, it isn't registering as a label at all. trying to figure how the label entry can be saved. not sure if I should save it as a variable and then display it or just display the same label in both frames.
import tkinter as tk
import tkinter.messagebox as box
import csv
from tkinter import *
window = tk.Tk()
window.state('zoomed')
window.title('freshta otdering system')
def show_frame(fram):
fram.tkraise()
frame2 = tk.Frame(window)
frame3 = tk.Frame(window)
for frame in (frame1, frame2, frame3):
frame.grid(row=0,column=0,sticky='nsew')
filepath = '/Users/adamcleaver/Desktop/ICT/SAT part 1 /orders.csv'
File = open(filepath)
reader = csv.reader(File)
Data = list (reader)
del(Data[0])
list_of_entries = []
for x in list(range(0,len(Data))):
list_of_entries.append(Data[x][0])
var = StringVar(value = list_of_entries)
listbox1 = Listbox(frame2, listvariable = var)
listbox1.place(x= 10, y = 220, height = 500, width = 200)
def update():
index = listbox1.curselection()[0]
Foodlabel3.config(text = Data[index][1]) and Foodlabel2.config(text = Data[index][1])
Drinkslabel3.config(text = Data[index][2]) and Drinkslabel2.config(text = Data[index][2])
Pricelabel3.config(text = Data[index][3]) and Pricelabel2.config(text = Data[index][3])
return None
#using update function within the button
button1 = tk.Button(frame2, text="Update", command=update, fg = "blue", bg='yellow')
button1.place(x=400, y=450, height = 75, width = 125)
button2 = tk.Button(frame2, text="continue", command= lambda:show_frame(frame3), fg = "blue", bg='yellow')
button2.place(x=500, y=450, height = 75, width = 125)
Foodlabel = Label(frame2, text="Food", font=('Arial',20,'bold'),bg = '#F0EAD6').place(x= 295, y= 200)
Drinkslabel = Label(frame2, text="Drinks",font=('Arial',20,'bold'),bg = '#F0EAD6').place(x= 295, y= 300)
Pricelabel = Label(frame2, text="Total price ($)",font=('Arial',20,'bold'),bg = '#F0EAD6').place(x= 275, y=400)
Foodlabel2 = Label(frame2, text="",font=('Arial',20),bg = '#F0EAD6')
Foodlabel2.place(x= 425 , y= 200)
Drinkslabel2 = Label(frame2, text="",font=('Arial',20),bg = '#F0EAD6')
Drinkslabel2.place(x= 425, y= 300)
Pricelabel2 = Label(frame2, text="",font=('Arial',20),bg = '#F0EAD6' )
Pricelabel2.place(x=425, y= 400)
#label for login
tk.Label(frame2, text = 'Ordering' ,font=('Arial',36), fg = 'red', bg = '#F0EAD6' ).place(x=0, y=125)
tk.Label(frame2, text = 'Your order :' ,font=('Arial',36), bg = '#F0EAD6' ).place(x= 320, y=125)
#==================Frame 3 code ========================================
#label for login
tk.Label(frame2, text = 'Ordering' ,font=('Arial',36), fg = 'red', bg = '#F0EAD6' ).place(x=0, y=125)
Foodlabel3 = Label(frame3, text="",font=('Arial',20),bg = '#F0EAD6')
Foodlabel3.place(x= 425 , y= 200)
Drinkslabel3 = Label(frame3, text="",font=('Arial',20),bg = '#F0EAD6')
Drinkslabel3.place(x= 425, y= 300)
Pricelabel3 = Label(frame3, text="",font=('Arial',20),bg = '#F0EAD6' )
Pricelabel3.place(x=425, y= 400)
frame3_btn = tk.Button(frame3, text='Enter',command=lambda:show_frame(frame1))
frame3_btn.pack(fill='x',ipady=15)
show_frame(frame1)
window.mainloop()
That is not how you use and. You need:
def update():
index = listbox1.curselection()[0]
Foodlabel3.config(text = Data[index][1])
Foodlabel2.config(text = Data[index][1])
Drinkslabel3.config(text = Data[index][2])
Drinkslabel2.config(text = Data[index][2])
Pricelabel3.config(text = Data[index][3])
Pricelabel2.config(text = Data[index][3])

Using validation on text entry box

I am trying to set up validation on text entry boxes. Three of the boxes need to only accept integers and one text as a postcode. I am not sure whether to do this in a function previously defined or when the entry boxes are created. Also how would i make the values from the text entry boxes be accessable in the function QuoteCreation. All my code is below.
from tkinter import *
class quote():
def __init__(self, master):
self.master=master
self.master.title("Quote Screen")
self.master.geometry("2100x1400")
self.master.configure(background = "white")
self.Borras = PhotoImage(file = "Borras.Logo.2.gif") #sets up image
self.Borras.image = self.Borras
self.BorrasLabel = Label(self.master, image = self.Borras, bg = "white")#puts image onto label
self.BorrasLabel.place(anchor=NW)
self.Title = Label(self.master, text = "New Quote", font = ("calibri", 20), bg = "White")
self.Title.place(x=650, y = 10)
self.SubmitButton = PhotoImage(file = "Submit.Button.gif") #sets up image
self.SubmitButton.image = self.SubmitButton
self.SubmitButtonLabel = Button(self.master, image = self.SubmitButton, bg = "white", command= self.QuoteCreation)#puts image onto a button
self.SubmitButtonLabel.place(x=900, y=290)
PostCodeVar = StringVar()
PostCodeEntry = Entry(master,width=50, font=20, textvariable=PostCodeVar)
PostCodeEntry.place(x = 20, y = 150)
PostCodeVar.set("Please enter the Post Code")
PostCodeValue = PostCodeVar.get()
HeightVar = StringVar()
HeightEntry = Entry(master, width=50, font=20, textvariable=HeightVar)
HeightEntry.place(x = 20, y = 220)
HeightVar.set("Please enter the Height")
HeightValue = HeightVar.get()
LengthVar = StringVar()
LengthEntry = Entry(master, width=50, font=20, textvariable=LengthVar)
LengthEntry.place(x = 20, y = 290)
LengthVar.set("Please enter the Length")
LengthValue = LengthVar.get()
PitchVar = StringVar()
PitchEntry = Entry(master, width=50, font=20, textvariable=PitchVar)
PitchEntry.place(x = 20, y = 360)
PitchVar.set("Please enter the Pitch")
PitchValue = PitchVar.get()
RiseVar = StringVar()
RiseEntry = Entry(master, width=50, font=20, textvariable=RiseVar)
RiseEntry.place(x = 20, y = 430)
RiseVar.set("Please enter the Rise")
RiseValue = RiseVar.get()
self.SubmitButton = PhotoImage(file = "Submit.Button.gif")
self.SubmitButton.image = self.SubmitButton
self.SubmitButtonLabel = Button(self.master, image = self.SubmitButton, bg = "white", command= self.QuoteCreation)#puts image onto a button
self.SubmitButtonLabel.place(x=900, y=290)
def on_button(self):
print(self.entry.get())
def QuoteCreation(self):
print(' ')
def quitWindow(self):
self.master.destroy()
def backToWelcome(self):
self.master.destroy()
You would set up separate functions to deal with the validation, when the submit button is pressed.
So, as an example, your submit button may look a bit like this:
submitButton = Button(master, text="Submit", command=validation)
The validation, in your case would then want to carry out these checks:
def validation():
postcode = PostCodeVar.get()
length = LengthVar.get()
pitch = PitchVar.get()
rise = RiseVar.get()
if postcodeCheck(postcode) == True and length.isdigit() == True and pitch.isdigit() == True and rise.isdigit() == True:
#carry out chosen process
In your case, you can try setting the postcode, length, pitch and height variables before calling the function, and setting them as global. The postcode should be created, and if it is okay, the function should then:
return True
...so it matches the outcome of the if statement.
I hope this is what you were looking for, and can adapt the example to your specific problem!

Categories