I noticed a lagging behavior when I dragged my Tkinter Root window across the screen (it does not have same motion speed as my mouse cursor). I have created a simple Tkinter app where one of the features is that user can select via button widget(s) to show/hide different Frame widgets which contains other child widgets. I have created all the required widget(s) during init() in a class.
In this example, lets say I have 4 Frame widgets (Frame A, B, C, D) and 4 buttons (Button A, B, C, D), respectively. Each Frame widget(s) contain several child widget(s). So, when I click Button A, the app will show Frame A using .grid(), and hide other Frame(s) using .grid_remove(). However, when I continue my clicking actions on the rest of the Button(s) to display & hide other Frame(s), I noticed it affected my Root window dragging motion when I want to move the app across my screen.
Code:
import tkinter as tk
from functools import partial
from tkinter import ttk
class AppGui(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self.grid_columnconfigure(index = 0, weight = 1)
self.grid_rowconfigure(index = 1, weight = 1)
self.main_interface()
def main_interface(self):
prnt = tk.Frame(self, highlightthickness = 0, bd = 0)
self.btn_a = tk.Button(prnt, relief = tk.GROOVE, text = 'Frame A', width = 12, font='Helvetica 11 bold')
self.btn_b = tk.Button(prnt, relief = tk.GROOVE, text = 'Frame B', width = 12, font='Helvetica 11 bold')
self.btn_c = tk.Button(prnt, relief = tk.GROOVE, text = 'Frame C', width = 12, font='Helvetica 11 bold')
self.btn_d = tk.Button(prnt, relief = tk.GROOVE, text = 'Frame D', width = 12, font='Helvetica 11 bold')
self.btn_a['command'] = partial(self.fr_sel_func, 'A')
self.btn_b['command'] = partial(self.fr_sel_func, 'B')
self.btn_c['command'] = partial(self.fr_sel_func, 'C')
self.btn_d['command'] = partial(self.fr_sel_func, 'D')
self.btn_a.grid(column = 0, row = 0, columnspan = 1, rowspan = 1, padx = (1,5), pady = (1,1), sticky = 'nwse')
self.btn_b.grid(column = 1, row = 0, columnspan = 1, rowspan = 1, padx = (1,5), pady = (1,1), sticky = 'nwse')
self.btn_c.grid(column = 2, row = 0, columnspan = 1, rowspan = 1, padx = (1,5), pady = (1,1), sticky = 'nwse')
self.btn_d.grid(column = 3, row = 0, columnspan = 1, rowspan = 1, padx = (1,1), pady = (1,1), sticky = 'nwse')
self.hashmap_fr_gui = {}
# self.create_fr_gui(): Function to create a Frame widget with all the child widgets.
# Store the Frame widget(s) in a hashmap
self.hashmap_fr_gui['A'] = self.create_fr_gui('A')
self.hashmap_fr_gui['B'] = self.create_fr_gui('B')
self.hashmap_fr_gui['C'] = self.create_fr_gui('C')
self.hashmap_fr_gui['D'] = self.create_fr_gui('D')
prnt.grid(column = 0, row = 0, columnspan = 1, rowspan = 1, padx = (2,1), pady = (1,1), sticky = 'nwse')
self.btn_a.invoke()
def fr_sel_func(self, hashmap_id):
if hashmap_id in self.hashmap_fr_gui:
for kw, tk_gui in self.hashmap_fr_gui.items():
if kw == hashmap_id:
tk_gui.grid(column = 0, row = 1, columnspan = 1, rowspan = 1, padx = (2,2), pady = (3,1), sticky = 'nwse')
else:
tk_gui.grid_remove()
def create_fr_gui(self, hashmap_id):
# Create Parent Frame GUI
prnt_gui = tk.Frame(self)
prnt_gui['bg'] = 'white'
prnt_gui.grid_columnconfigure(index = 0, weight = 1)
prnt_gui.grid_columnconfigure(index = 1, weight = 1)
prnt_gui.grid_rowconfigure(index = 0, weight = 1)
prnt_gui.grid_rowconfigure(index = 1, weight = 1)
child_gui_a = self.create_fr_child(prnt_gui, 'Subframe 1{}'.format(hashmap_id))
child_gui_b = self.create_fr_child(prnt_gui, 'Subframe 2{}'.format(hashmap_id))
child_gui_c = self.create_fr_child(prnt_gui, 'Subframe 3{}'.format(hashmap_id))
child_gui_d = self.create_fr_child(prnt_gui, 'Subframe 4{}'.format(hashmap_id))
child_gui_a.grid(column = 0, row = 0, columnspan = 1, rowspan = 1, padx = (1,1), pady = (1,1), sticky = 'nwse')
child_gui_b.grid(column = 1, row = 0, columnspan = 1, rowspan = 1, padx = (3,1), pady = (1,1), sticky = 'nwse')
child_gui_c.grid(column = 0, row = 1, columnspan = 1, rowspan = 1, padx = (1,1), pady = (3,1), sticky = 'nwse')
child_gui_d.grid(column = 1, row = 1, columnspan = 1, rowspan = 1, padx = (3,1), pady = (3,1), sticky = 'nwse')
return prnt_gui
def create_fr_child(self, prnt, panel_name):
# Create Child Frame GUI
child_gui = tk.Frame(prnt, highlightthickness = 1, highlightbackground = 'black')
child_gui.grid_columnconfigure(index = 0, weight = 1)
child_gui.grid_columnconfigure(index = 1, weight = 10)
child_gui.grid_rowconfigure(index = 0, weight = 0)
child_gui.grid_rowconfigure(index = 1, weight = 1)
name_tk_lb = tk.Label(child_gui, text = panel_name, font = 'Helvetica 14 bold'
, justify = tk.LEFT, anchor = 'nw')
name_tk_lb.grid(column = 0, row = 0, columnspan = 2, rowspan = 1, padx = (5,1), pady = (5,5), sticky = 'nwse')
#####################################################################################################################
# Left Side Grid Widget(s)
left_grid = tk.Frame(child_gui)
left_grid.grid_columnconfigure(index = 0, weight = 1)
left_grid.grid(column = 0, row = 1, columnspan = 1, rowspan = 1, padx = (20,1), pady = (1,1), sticky = 'nwse')
tk_lb = tk.Label(left_grid, text = 'Combobox: ', font = 'Helvetica 12 italic', width = 12
, justify = 'left', anchor = 'w')
tk_lb.grid(column = 0, row = 0, columnspan = 1, rowspan = 1, padx = (1,5), pady = (1,1), sticky = 'nwse')
ttk_cbox = ttk.Combobox(left_grid, values = [], width=13, state='readonly', font = 'Helvetica 11')
ttk_cbox.grid(column = 0, row = 1, columnspan = 1, rowspan = 1, padx = (1,5), pady = (5,1), sticky = 'nwse')
ttk_cbox.unbind_class("TCombobox", "<MouseWheel>")
tk_btn = tk.Button(left_grid, relief = tk.GROOVE, width = 10, height = 1, font = 'Helvetica 12')
tk_btn['text'] = 'Button'
tk_btn.grid(column = 0, row = 2, columnspan = 1, rowspan = 1, padx = (1,5), pady = (100,1), sticky = 'nwse')
#####################################################################################################################
# Right Side Grid Widget(s)
right_grid = tk.Frame(child_gui)
right_grid.grid_columnconfigure(index = 0, weight = 5)
right_grid.grid_columnconfigure(index = 1, weight = 10)
right_grid.grid_columnconfigure(index = 2, weight = 1)
right_grid.grid(column = 1, row = 1, columnspan = 1, rowspan = 1, padx = (10,20), pady = (1,1), sticky = 'nwse')
for i in range(0, 6):
right_grid.grid_rowconfigure(index = i, weight = 1, min = 50)
tk_lb = tk.Label(right_grid, text = 'Scalebar {}'.format(i + 1), font = 'Helvetica 12', justify = 'right', anchor = 'ne')
scl_var = tk.StringVar()
sbox_var = tk.StringVar()
tk_scl = tk.Scale(right_grid, from_=1, to=10, variable=scl_var, orient='horizontal', showvalue=0)
tk_sbox = tk.Spinbox(right_grid, width = 4, textvariable = sbox_var, from_=1, to=10
, highlightbackground="black", highlightthickness=1, font = 'Helvetica 12')
scl_var.set(1)
tk_lb.grid(column = 0, row = i, columnspan = 1, rowspan = 1, padx = (3,1), pady = (3,1), sticky = 'nwes')
tk_scl.grid(column = 1, row = i, columnspan = 1, rowspan = 1, padx = (3,1), pady = (4,1), sticky = 'nwe')
tk_sbox.grid(column = 2, row = i, columnspan = 1, rowspan = 1, padx = (3,3), pady = (3,1), sticky = 'nwe')
return child_gui
if __name__ == '__main__':
tk_root = tk.Tk()
tk_root_width = 890
tk_root_height = 600
screen_width = tk_root.winfo_screenwidth()
screen_height = tk_root.winfo_screenheight()
x_coordinate = int((screen_width/2) - (tk_root_width/2))
y_coordinate = int((screen_height/2) - (tk_root_height/2))
tk_root.geometry("{}x{}+{}+{}".format(tk_root_width, tk_root_height, x_coordinate, y_coordinate))
app_gui = AppGui(tk_root)
tk_root.grid_columnconfigure(index = 0, weight = 1)
tk_root.grid_rowconfigure(index = 0, weight = 1)
app_gui.grid(column = 0, row = 0, columnspan = 1, rowspan = 1, padx = (1,1), pady = (1,1), sticky = 'nwse')
tk_root.mainloop()
The issue seem to be mitigated when i experimented with .grid_destroy() on the Frame widget(s). However, I prefer not to use .grid_destroy(), otherwise I have to re-create my widget(s) again. So to solve this issue, do I have to use .grid_remove() on every child widgets within my Frame widget(s)? Or is there any other advise/solution to this.
EDIT 1: To replicate the lagging behavior when dragging the app window, user need to click each button(s) to display each Frame widgets at least once.
I experienced the same behavior with my Tkinter app and I found out that it's caused by my mouse (SteelSeries Sensei Ten).
When I tried moving the window with a different generic mouse, the "slugish" movement was gone. Finally, I tried messing with my mouse settings and it turned out that lowering my polling rate from 1000 to 250 Hz fixes it as well.
I also found out that this behavior is dependent alongside the polling rate on the number of used widgets and the size of the window.
I guess that a better solution would be to limit the "refresh rate" of your application locally. However, I'm not sure if that's possible.
EDIT:
It is possible actually.
from time import sleep
def on_configure(e):
if e.widget == tk_root:
sleep(0.015)
if __name__ == '__main__':
tk_root = tk.Tk()
tk_root.bind("<Configure>", on_configure)
tk_root_width = 890
tk_root_height = 600
screen_width = tk_root.winfo_screenwidth()
screen_height = tk_root.winfo_screenheight()
x_coordinate = int((screen_width/2) - (tk_root_width/2))
y_coordinate = int((screen_height/2) - (tk_root_height/2))
tk_root.geometry("{}x{}+{}+{}".format(tk_root_width, tk_root_height, x_coordinate, y_coordinate))
app_gui = AppGui(tk_root)
tk_root.grid_columnconfigure(index = 0, weight = 1)
tk_root.grid_rowconfigure(index = 0, weight = 1)
app_gui.grid(column = 0, row = 0, columnspan = 1, rowspan = 1, padx = (1,1), pady = (1,1), sticky = 'nwse')
tk_root.mainloop()
This fixed it for me.
Related
Hey I would like to create a frame which contains a Listbox and some buttons. What I would like to do is to somehow pass as an argument a name of this listbox. This is my current code in which I set the name of this listbox to master.thisListbox but I would like to pass it somehow as argument. Is it possible or should I separately crate a listbox in my App and the pass it as an argument to a frame? I'm going to create a lot of such listboxes in my App hence the name of listbox shouldn't be the same. I'm pretty new in OOP.
class myApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.dateFrame = DateFrame(self)
self.dateFrame.grid(row = 0, column = 0)
print(self.day.get())
self.myFrame = ListboxFrame(self, "Label!", [1,2,3])
self.myFrame.grid(row = 1, column = 0)
x = self.thisListbox.get(0, END)
print(x)
class DateFrame(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
# Day
ttk.Label(self, text = "Day", width = 4).grid(row = 0, column = 0, padx = 3, pady = 3)
master.day = IntVar(master, value = 31)
self.dayCB = ttk.Combobox(self, values = [x for x in range(1, 32)], textvariable = master.day, width = 4)
self.dayCB.grid(row = 1, column = 0, padx = 3, pady = 3)
# Month
ttk.Label(self, text = "Month", width = 6).grid(row = 0, column = 1, padx = 3, pady = 3)
self.month = IntVar(master, value = 12)
self.monthCB = ttk.Combobox(self, values = [x for x in range(1, 13)], textvariable = self.month, width = 4)
self.monthCB.grid(row = 1, column = 1, padx = 3, pady = 3)
# Year
ttk.Label(self, text = "Year", width = 4).grid(row = 0, column = 2, padx = 3, pady = 3)
self.year = IntVar(master, value = 2021)
self.yearCB = ttk.Spinbox(self, from_ = 2020, to = 2100, textvariable = self.year, width = 6)
self.yearCB.grid(row = 1, column = 2, padx = 3, pady = 3)
class ListboxFrame(ttk.Frame):
def __init__(self, master, labelText, values, selectmode = "extended", height = 6, width = 30):
ttk.Frame.__init__(self, master)
# Listbox
ttk.Label(self, text = labelText).grid(row = 0, column = 0, columnspan = 3)
master.thisListbox = tk.Listbox(self, selectmode = selectmode, height = height, width = width)
master.thisListbox.grid(row = 1, column = 0, columnspan = 3, padx = 2, pady = 2)
# Entry
self.entry = ttk.Entry(self)
self.entry.grid(row = 2, column = 0, padx = 2, pady = 2)
# Buttons
self.addButton = ttk.Button(self, text = "Add", width = 4, command = self.Add)
self.addButton.grid(row = 2, column = 1, padx = 2, pady = 2)
self.deleteButton = ttk.Button(self, text = "Delete", width = 6, command = self.Delete)
self.deleteButton.grid(row = 2, column = 2, padx = 2, pady = 2)
for v in values:
master.thisListbox.insert(END, v)
def Add(self):
if self.entry.get() == "": return
master.thisListbox.insert(END, self.entry.get())
self.entry.delete(0, END)
def Delete(self):
for index in reversed(master.thisListbox.curselection()):
master.thisListbox.delete(index)
# listbox.config(height = listbox.size())
I'm trying to create an app that has 2 windows. The first window (A) is only called the first time the app is ran, and then opens window (B). For all future events, only window (B) is called. This is the following code:
# Script Counter/Setup
def read_counter():
if path.exists("counter.json"):
return loads(open("counter.json", "r").read()) + 1
else:
info = tk.Tk()
info.title("Setup")
info.geometry("350x120")
info.grid_columnconfigure((0, 2), weight = 1)
count = tk.Label(info, text = "Previous Post Number")
string = tk.StringVar()
count_input = tk.Entry(info, textvariable = string)
val = string.get()
def destroy_get():
val = int(count_input.get())
info.quit()
return val
count_button = tk.Button(info, text = "Done!", command = destroy_get)
tk.Label(info, text = "Setup", font='Helvetica 18 bold').grid(row = 0, column = 1, padx = 5, pady = 5)
count.grid(row = 1, column = 0, padx = 5, pady = 5)
count_input.grid(row = 1, column = 2, padx = 5, pady = 5)
count_button.grid(row = 2, column = 1, padx = 5, pady = 5)
info.mainloop()
# info.destroy()
return destroy_get()
def write_counter():
with open("counter.json", "w") as f:
f.write(dumps(counter))
counter = read_counter()
atexit.register(write_counter)
folders = ["to_post/", "not_posted/", "posted"]
for folder in folders:
if not path.exists(folder):
os.mkdir(folder)
print(os.getcwd())
# GUI
window = tk.Tk()
window.title("Confessions Bot")
window.geometry("600x350")
window.grid_columnconfigure((0,2), weight = 1)
label_tell_account = tk.Label(window, text = "Tellonym Account")
label_tell_password = tk.Label(window, text = "Tellonym Password")
label_ig_account = tk.Label(window, text = "Instagram Account")
label_ig_password = tk.Label(window, text = "Instagram Password")
tell_account = tk.Entry(window)
tell_password = tk.Entry(window)
ig_account = tk.Entry(window)
ig_password = tk.Entry(window)
image = ImageTk.PhotoImage(Image.open("logo.png"))
tk.Label(window, image = image).grid(row = 0, column = 1, padx = 10, pady = 10)
label_tell_account.grid(row = 1, column = 0)
tell_account.grid(row = 1, column = 2, padx = 10, pady = 10)
label_tell_password.grid(row = 2, column = 0, padx = 10, pady = 10)
tell_password.grid(row = 2, column = 2, padx = 10, pady = 10)
label_ig_account.grid(row = 3, column = 0, padx = 10, pady = 10)
ig_account.grid(row = 3, column = 2, padx = 10, pady = 10)
label_ig_password.grid(row = 4, column = 0, padx = 10, pady = 10)
ig_password.grid(row = 4, column = 2, padx = 10, pady = 10)
# run.grid(row = 5, column = 1, padx = 10, pady = 10)
window.mainloop()
When this is ran I get _tkinter.TclError: image "pyimage1" doesn't exist. I read that this happens since I haven't destroyed my initial window. If I change destroy_get() to have info.destroy() I'm no longer able to get the the entry from window A.
This is my first time using Tkinter and coding in general so any help is welcome.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm using the Scrolled Text widget in Tkinter, but when I call the destroy() method on it the Box disappears but the scroll bar stays. I provided some images so you can get a better understanding of what I'm talking about.
How can I fix this?
Here is the code, I'm talking about the item_description widget.
def add_item():
global options
global add
global remove
global display
add.config(state = "disabled", relief = "sunken")
remove.config(state = "disabled")
display.config(state = "disabled")
name_label = Label(options, text = "Item Name")
name_label.grid(row = 1, column = 0, columnspan = 3, sticky = "w")
item_name = Entry(options, width = 35)
item_name.grid(row = 2, column = 0, columnspan = 3, sticky = "w")
description_label = Label(options, text = "Item Description")
description_label.grid(row = 3, column = 0, columnspan = 3, sticky = "w")
item_description = ScrolledText(options, width = 25, height = 5)
item_description.grid(row = 4, column = 0, columnspan = 3, sticky = "w")
price_label = Label(options, text = "Item Price")
price_label.grid(row = 5, column = 0, columnspan = 3, sticky = "w")
item_price = Entry(options, width = 5)
item_price.grid(row = 6, column = 0, sticky = "w", columnspan = 3)
item_price.insert(0, "$0.00")
stock_label = Label(options, text = "Stock")
stock_label.grid(row = 7, column = 0, columnspan = 3, sticky = "w")
item_stock = Entry(options, width = 5)
item_stock.grid(row = 8, column = 0, sticky = "w", columnspan = 3)
calories_label = Label(options, text = "Calories")
calories_label.grid(row = 9, column = 0, sticky = "w", columnspan = 3)
item_calories = Entry(options, width = 5)
item_calories.grid(row = 10, column = 0, sticky = "w", columnspan = 3)
date_label = Label(options, text = "Expiry Date")
date_label.grid(row = 11, column = 0, sticky = "w", columnspan = 3)
item_expiry_date = Entry(options, width = 12)
item_expiry_date.grid(row = 12, column = 0, sticky = "w", columnspan = 3)
item_expiry_date.insert(0, "dd/mm/yyyy")
stock_add = Button(options, text = "Add", borderwidth = 2, relief = "groove",
command = lambda: add_to_stock(item_name.get(),
item_description.get("1.0", "end-1c"),
item_price.get(),
item_stock.get(),
item_calories.get(),
item_expiry_date.get()))
stock_add.grid(row = 13, column = 0, sticky = "w", columnspan = 3)
global widgets_add
widgets_add = [name_label, item_name, description_label, item_description, price_label, item_price,
stock_label, item_stock, calories_label, item_calories, date_label, item_expiry_date, stock_add]
Here is the code where I remove all the widgets from the widgets_add list, which is made at the end of the previous code.
def remove_add():
# Remove item adding dialog
global widgets_add
for widget in widgets_add:
widget.destroy()
The issue is that the ScrolledText widget actually creates
Frame
Scrollbar
ScrolledText
but only returns a reference to ScrolledText. When you destroy() that, the Frame and Scrollbar get left behind.
The easiest solution would be to add all of your controls to a Frame instance and destroy() that instead. In this way you don't have to keep track of them in a separate list.
So, assuming options is your Tk instance:
def add_item():
global options
global add
global remove
global display
add.config(state = "disabled", relief = "sunken")
remove.config(state = "disabled")
display.config(state = "disabled")
options_frame = Frame(options)
name_label = Label(options_canvas, text = "Item Name")
name_label.grid(row = 1, column = 0, columnspan = 3, sticky = "w")
item_name = Entry(options_canvas, width = 35)
item_name.grid(row = 2, column = 0, columnspan = 3, sticky = "w")
description_label = Label(options_canvas, text = "Item Description")
description_label.grid(row = 3, column = 0, columnspan = 3, sticky = "w")
item_description = ScrolledText(options_canvas, width = 25, height = 5)
item_description.grid(row = 4, column = 0, columnspan = 3, sticky = "w")
price_label = Label(options_canvas, text = "Item Price")
price_label.grid(row = 5, column = 0, columnspan = 3, sticky = "w")
item_price = Entry(options_canvas, width = 5)
item_price.grid(row = 6, column = 0, sticky = "w", columnspan = 3)
item_price.insert(0, "$0.00")
stock_label = Label(options_canvas, text = "Stock")
stock_label.grid(row = 7, column = 0, columnspan = 3, sticky = "w")
item_stock = Entry(options_canvas, width = 5)
item_stock.grid(row = 8, column = 0, sticky = "w", columnspan = 3)
calories_label = Label(options_canvas, text = "Calories")
calories_label.grid(row = 9, column = 0, sticky = "w", columnspan = 3)
item_calories = Entry(options_canvas, width = 5)
item_calories.grid(row = 10, column = 0, sticky = "w", columnspan = 3)
date_label = Label(options_canvas, text = "Expiry Date")
date_label.grid(row = 11, column = 0, sticky = "w", columnspan = 3)
item_expiry_date = Entry(options_canvas, width = 12)
item_expiry_date.grid(row = 12, column = 0, sticky = "w", columnspan = 3)
item_expiry_date.insert(0, "dd/mm/yyyy")
stock_add = Button(options_canvas, text = "Add", borderwidth = 2, relief = "groove",
command = lambda: add_to_stock(item_name.get(),
item_description.get("1.0", "end-1c"),
item_price.get(),
item_stock.get(),
item_calories.get(),
item_expiry_date.get()))
stock_add.grid(row = 13, column = 0, sticky = "w", columnspan = 3)
def remove_add():
# Remove item adding dialog
global options_frame
options_frame.destroy()
Good afternoon,
I've been trying for two days to solve this problem and desperate, I am looking for your help. I want to show a plot (using matplotlib) within my tkinter application (not opening it in a different window) and the problem is that when I press any of the toolbar buttons as soon as I cross with the mouse coursor the lines of the plot, the plot disappears for a brief moment and appears again, but the toolbar buttons disappear until I cross them again with the mouse coursor. So for the button to appear back I should cross it and cross out off the button.
I noticed that if I change the background image (just the color, placed in label) the disappeared buttons are replaced with that color, so it seems that when I cross the lines of the plot everything in the Label except the plot is overlayed by the background.
Regards,
Wladyslaw
The code is:
import tkinter as tk
from tkinter.ttk import *
from tkinter import *
import tkinter.font as tkFont
from tkinter import scrolledtext
import logging
from PIL import Image, ImageTk
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import numpy as np
from matplotlib.figure import Figure
import numpy as np
import sys
if sys.version_info[0] < 3:
import Tkinter as tk
else:
import tkinter as tk
from matplotlib.backends import _backend_tk
from matplotlib.backends.backend_agg import FigureCanvasAgg
class WidgetLogger(logging.Handler):
def __init__(self, widget):
logging.Handler.__init__(self)
self.setLevel(logging.INFO)
self.widget = widget
self.widget.config(state='disabled')
def emit(self, record):
self.widget.config(state='normal')
# Append message (record) to the widget
self.widget.insert(tk.END, self.format(record) + '\n')
self.widget.see(tk.END) # Scroll to the bottom
self.widget.config(state='disabled')
class Product:
def __init__(self, window):
self.wind = window
self.wind.geometry("1060x700")
self.wind.title('Artificial intelligence based pricer')
self.wind.lift()
#self.wind.resizable(width=False, height=False)
background_color = '#526b70'
background_color2 = '#e4e8eb'
background_color3 = '#e4e8eb'
background_color4 = '#c4cfd2'
text_color = 'white'
style = ttk.Style()
style.configure("TProgressbar", background=background_color)
img = Image.open('Files/Images/background_image.jpg')
img = ImageTk.PhotoImage(img)
background = tk.Label(self.wind, image=img, bd=0)
background.grid(row = 0, column = 0, rowspan = 8, columnspan = 5)
background.image = img
img2 = Image.open('Files/Images/background_image2.jpg')
img2 = ImageTk.PhotoImage(img2)
background2 = tk.Label(self.wind, image=img2, bd=0)
background2.grid(row = 9, column = 0, rowspan = 10, columnspan = 10)
background2.image = img2
########## LEFT TOP SIDE ##############################
fontStyleTitle = tkFont.Font(family="Times New Roman (Times)", size=12, weight='bold')
fontStyleText = tkFont.Font(family="Arial", size=10, weight='bold')
Label1 = Label(background, text = ' ')
Label1.grid(row = 0, column = 0)
Label1.configure(background=background_color)
Label2 = Label(background, text = 'GLOBAL CONFIGURATION', fg=text_color, font=fontStyleTitle)
Label2.grid(row = 1, column = 1, padx = 3, columnspan = 2, sticky = W)
Label2.configure(background=background_color)
Label3 = Label(background, text = 'Shop ID: ', fg=text_color, font=fontStyleText)
Label3.grid(row = 2, column = 1, pady = 4, sticky = W)
Label3.configure(background=background_color)
self.shop = Entry(background)
self.shop.focus()
self.shop.grid(row = 2, column = 2)
self.shop.configure(background=background_color3)
Label4 = Label(background, text = 'Item ID: ', fg=text_color, font=fontStyleText)
Label4.grid(row = 3, column = 1, sticky = W)
Label4.configure(background=background_color)
self.item = Entry(background)
self.item.grid(row = 3, column = 2)
self.item.configure(background=background_color3)
Label5 = Label(background, text = '')
Label5.grid(row = 4, column = 1)
Label5.configure(background=background_color)
Label6 = Label(background, text = 'ANN CONFIGURATION', font = fontStyleTitle, fg=text_color)
Label6.grid(row = 5, column = 1, padx = 3, columnspan = 2, sticky = W)
Label6.configure(background=background_color)
Label7 = Label(background, text = 'Model: ', fg=text_color, font=fontStyleText)
Label7.grid(row = 6, column = 1, pady = 4, sticky = W)
Label7.configure(background=background_color)
self.model = Entry(background)
self.model.grid(row = 6, column = 2)
self.model.configure(background=background_color3)
Label8 = Label(background, text = 'Test set: ', fg=text_color, font=fontStyleText)
Label8.grid(row = 7, column = 1, sticky = W)
Label8.configure(background=background_color)
self.test_set = Entry(background)
self.test_set.grid(row = 7, column = 2)
self.test_set.configure(background=background_color3)
Button1 = tk.Button(background, bg=background_color2, text = 'Calculate performance')
Button1.grid(row = 8, column = 1, padx = 50, pady = 10, columnspan = 2, sticky = W+E)
#Button1.configure(background=background_color)
########## CENTER TOP SIDE ############################
Label9 = Label(background, text = 'ANN MODEL PERFORMANCE', font=fontStyleTitle, fg=text_color)
Label9.grid(row = 1, column = 3, padx = 40, sticky = W)
Label9.configure(background=background_color)
performace = Text(background, height=8, width=50)
performace.grid(row = 2, column = 3, padx = 40, rowspan = 6)
temporalText = '''MSE of standarized mean predictions: 700,5496
MSE of standarized ANN predictions: 700,5496
MSE of deseasonalized mean predictions: 700,5496
MSE of deseasonalized ANN predictions: 700,5496
MSE of seasonalized mean predictions: 700,5496
MSE of seasonalized ANN predictions: 700,5496'''
performace.insert(tk.END, temporalText)
performace.configure(background=background_color3)
Widget_Logger = WidgetLogger(performace)
progress = Progressbar(background, style='TProgressbar', orient = HORIZONTAL, length = 100, mode = 'determinate')
progress.grid(row = 8, column = 3, padx = 40, sticky = W+E)
#progress.configure(background=background_color)
########## RIGHT TOP SIDE #############################
Label10 = Label(background, text = ' ')
Label10.grid(row = 0, column = 6)
Label10.configure(background=background_color)
Label11 = Label(background, text = "PREDICTION'S CONFIGURATION", font=fontStyleTitle, fg=text_color)
Label11.grid(row = 1, column = 4, padx = 3, columnspan = 2, sticky = W)
Label11.configure(background=background_color)
Label12 = Label(background, text = 'Precision: ', fg=text_color, font=fontStyleText)
Label12.grid(row = 2, column = 4, pady = 4, sticky = W)
Label12.configure(background=background_color)
self.precision = Entry(background)
self.precision.focus()
self.precision.grid(row = 2, column = 5)
self.precision.configure(background=background_color3)
Label13 = Label(background, text = 'Max. price multiplicator: ', fg=text_color, font=fontStyleText)
Label13.grid(row = 3, column = 4, sticky = W)
Label13.configure(background=background_color)
self.max_price_multiplicator = Entry(background)
self.max_price_multiplicator.grid(row = 3, column = 5)
self.max_price_multiplicator.configure(background=background_color3)
Label14 = Label(background, text = 'Delta multiplicator: ', fg=text_color, font=fontStyleText)
Label14.grid(row = 4, column = 4, pady = 4, sticky = W)
Label14.configure(background=background_color)
self.delta_multiplicator = Entry(background)
self.delta_multiplicator.grid(row = 4, column = 5)
self.delta_multiplicator.configure(background=background_color3)
Label15 = Label(background, text = 'Item cost: ', fg=text_color, font=fontStyleText)
Label15.grid(row = 5, column = 4, sticky = W)
Label15.configure(background=background_color)
self.item_cost = Entry(background)
self.item_cost.grid(row = 5, column = 5)
self.item_cost.configure(background=background_color3)
Radiobutton(background, text = "absolute", variable = (background,"1"), value = "1", indicator = 0, background = "light blue", activebackground=background_color2, activeforeground='black').grid(row = 6, column = 4, sticky = E)
Radiobutton(background, text = "mean price multiplicator", variable = (background,"1"), value = "2", indicator = 0, background = "light blue", activebackground=background_color2, activeforeground='black').grid(row = 6, column = 5, pady = 4, sticky = W)
Label16 = Label(background, text = 'Fixed costs: ', fg=text_color, font=fontStyleText)
Label16.grid(row = 7, column = 4, sticky = W)
Label16.configure(background=background_color)
self.fixed_costs = Entry(background)
self.fixed_costs.grid(row = 7, column = 5)
self.fixed_costs.configure(background=background_color3)
Button2 = tk.Button(background, bg=background_color2, text = 'Calculate predictions')
Button2.grid(row = 8, column = 4, padx = 80, pady = 10, columnspan = 2, sticky = W+E)
Label17 = Label(background, text = ' ')
Label17.grid(row = 0, column = 6, sticky = W)
Label17.configure(background=background_color)
########## LEFT BOTTOM SIDE ###########################
Label18 = Label(background, text = ' ')
Label18.grid(row = 9, column = 1)
Label18.configure(background=background_color)
fig = Figure(figsize=(6, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
canvas = FigureCanvasTkAgg(fig, master=background2)
canvas.draw()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
toolbarFrame = Frame(master=background2)
toolbarFrame.pack(side=TOP, fill=BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, toolbarFrame)
toolbar.update()
canvas.mpl_connect("key_press_event", on_key_press)
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
if __name__ == '__main__':
window = Tk()
application = Product(window)
window.mainloop()```
Trying to split my parent window in several functional parts, one of which will be dealing with weather
data and etc and another one will be located in the right side and contain the map image, preferably extending at full height. The image doesn't want to come up though.. Please help
import pyowm
from tkinter import *
import tkinter.messagebox
from PIL import Image, ImageTk
owm = pyowm.OWM('....') # You MUST provide a valid API key
class MyWindow(tkinter.Frame):
def __init__(self, win):
super(MyWindow, self).__init__()
self.lbl=Label(win, text="Weather info", fg='black', font=("Helvetica", 11))
self.lbl1=Label(win, text='Wind speed')
self.lbl2=Label(win, text='Wind direction')
self.lbl.grid(row = 0, column = 0, sticky = W, pady = 2)
self.lbl1.grid(row = 1, column = 0, sticky = W, pady = 2)
self.lbl2.grid(row = 2, column = 0, sticky = W, pady = 2)
# widgets for destination and weather output
self.e1=Entry()
self.e2=Entry()
self.e3=Entry(bd=3)
# this will arrange entry widgets
self.e1.grid(row = 0, column = 1, pady = 2)
self.e2.grid(row = 1, column = 1, pady = 2)
self.e3.grid(row = 2, column = 1, pady = 2)
self.btn1 = Button(win, text='Get weather', command=self.getWeather)
self.btn1.grid(row = 3, column = 1, pady = 2)
self.btn1.bind('<Button-1>', self.getWeather)
img = Image.open(r"/User/.../pic.png")
photo = ImageTk.PhotoImage(img)
# setting image with the help of label
self.imgLBL = Label(self, image = photo)
self.imgLBL.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5)
self.imgLBL.image = photo
#### Get weather function, etc...###
window=Tk()
mywin=MyWindow(window)
window.title('name')
window.geometry("2732x2048")
window.configure(bg='grey')
window.mainloop()
Replace last few lines with this:
self.photo = ImageTk.PhotoImage(Image.open(r"/User/.../pic.png"))
# setting image with the help of label
self.imgLBL = Label(window, image=self.photo)
self.imgLBL.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5)
self.imgLBL.image = self.photo