How do I align rows of two frames in tkinter? - python

I have two frames in tkinter. One of them has labels, while the other has text fields and buttons. When a user clicks a button, more fields get added horizontally in the second frame. Both frames are connected to one vertical scrollbar, and the second frame has its own horizontal scrollbar. How can I make it so the first row of the first frame is aligned with the first row of the second frame?
I would like the fields to be aligned with A, B, C labels
from tkinter import *
import pyodbc # Importing for storing in a DB
from tkinter import messagebox
import getpass
import os
from datetime import datetime
from tkinter import ttk
import win32com.client
import openpyxl
from openpyxl import load_workbook
from tkcalendar import Calendar, DateEntry
global totalItems
global itemNum
global sizeList
global typeList
global qtyList
global actualQtyList
actualQtyList=[]
itemNum=0
def myfunction(event):
#canvas.configure(scrollregion=canvas.bbox("all"),height=650)
canvas.configure(scrollregion=canvas.bbox("all"), height=630)
def myfunction2(event):
canvasForCustomers.configure(scrollregion=canvasForCustomers.bbox("all"),height=645,width=900)
def multiple_yview(*args):
canvas.yview(*args)
canvasForCustomers.yview(*args)
def addNewCustomer():
global totalItems
global itemNum
padxValue=0
lbFrame_Customer=ttk.LabelFrame(frameForOfferCreationFilter,text="Customer")
cb_customer=ttk.Combobox(lbFrame_Customer,state='readonly',values=customerList,width=6)
cb_customer.grid(row=0,column=0)
lbFrame_ShipDate=ttk.LabelFrame(frameForOfferCreationFilter,text="Ship Date")
cal_ShipDate=DateEntry(lbFrame_ShipDate)
cal_ShipDate.grid(row=0,column=0)
lbFrame_PackedDateRange=ttk.LabelFrame(frameForOfferCreationFilter,text="Packed Date Range")
cal_FromDate=DateEntry(lbFrame_PackedDateRange)
lb_hyphen=ttk.Label(lbFrame_PackedDateRange,text="-")
cal_ToDate = DateEntry(lbFrame_PackedDateRange)
cal_FromDate.grid(row=0,column=0)
lb_hyphen.grid(row=0,column=1)
cal_ToDate.grid(row=0,column=2)
lbFrame_Customer.grid(row=0,column=itemNum,columnspan=1,padx=padxValue)
lbFrame_ShipDate.grid(row=0,column=itemNum+1,columnspan=1,padx=padxValue)
lbFrame_PackedDateRange.grid(row=0,column=itemNum+2,columnspan=2,padx=padxValue)
lb_CaseSize = ttk.Label(frameForOfferCreationFilter, text="Case Size", justify="center").grid(row=1, column=itemNum,padx=padxValue)
if itemNum%2!=0:
padxValue=20
else:
padxValue=0
indexNum=0
if indexNum%2==0:
padyValue2=0
else:
padyValue2=5
# frameForOfferCreation=Frame(canvasForCustomers,bg='yellow')
# frameForOfferCreation.grid(row=2,column=0,columnspan=6)
for indexNum in range(totalItems):
txt_CaseSize = ttk.Entry(frameForOfferCreationItems, width=7)
txt_CaseSize.grid(row=indexNum, column=itemNum, padx=10+padxValue,pady=padyValue2,sticky=S)
if indexNum % 2 == 0:
padyValue2 = 4
else:
padyValue2 = 0
itemNum = itemNum + 7
root_1 = Tk()
w, h = root_1.winfo_screenwidth(), root_1.winfo_screenheight()
root_1.geometry("%dx%d+0+0" % (w, h))
root_1.title("Sales Allocation Application")
allItems=['A','B','C']
############################ Getting Customers
allCustomers=['X','Y','Z']
customerList=[]
for item in allCustomers:
customerList.append(item[0])
tab_parent = ttk.Notebook(root_1)
tab_parent.pack(expand=1, fill='both')
tab_OfferPage = ttk.Frame(tab_parent)
tab_EditPage=ttk.Frame(tab_parent)
# tab_AllOffers = ttk.Frame(tab_parent)
tab_parent.add(tab_OfferPage, text='Create New Offer')
tab_parent.add(tab_EditPage,text="Edit Existing Offers")
lbFrm_ExistingItems=ttk.LabelFrame(tab_OfferPage,text="Items")
lbFrm_ExistingItems.pack(expand=1,fill='both')
canvas = Canvas(lbFrm_ExistingItems,width=300,height=650) # ,bg="#F4F3F1") width 400
canvas.grid(row=0, column=0,sticky=N)
frameOfItems = Frame(canvas,bg='green')
scrollBar = ttk.Scrollbar(lbFrm_ExistingItems, orient="vertical", command=multiple_yview) # canvas.yview)
canvas.configure(yscrollcommand=scrollBar.set)
frameOfItems.bind("<Configure>", myfunction)
scrollBar.grid(row=0, column=0, sticky=N + S + W) # , sticky=N + S + W)
canvas.create_window((0, 0), window=frameOfItems, anchor='nw')
canvasForCustomers=Canvas(lbFrm_ExistingItems,bg="red",width=900)
canvasForCustomers.grid(row=0, column=1,sticky=N+S)
frameForOfferCreationItems=Frame(canvasForCustomers,bg='pink')
frameForOfferCreationItems.bind("<Configure>", myfunction2)
frameForOfferCreationFilter=Frame(canvasForCustomers,bg='yellow')
frameForOfferCreationFilter.bind("<Configure>", myfunction2)
canvasForCustomers.create_window((0,0),window=frameForOfferCreationFilter,anchor='nw')
canvasForCustomers.create_window((0,80),window=frameForOfferCreationItems,anchor='nw')
btn_addCustomer=ttk.Button(lbFrm_ExistingItems,text="Add\nCustomer",command=addNewCustomer).grid(row=0,column=2,sticky=N+E)
btn_loadExisting=ttk.Button(lbFrm_ExistingItems,text="Load Existing\nOpen Offers").grid(row=0,column=3,sticky=N+E)
totalItems=len(allItems)
scrollBarHorizontal = ttk.Scrollbar(lbFrm_ExistingItems, orient="horizontal", command=canvasForCustomers.xview)
canvasForCustomers.configure(xscrollcommand=scrollBarHorizontal.set)
scrollBarHorizontal.grid(row=1, column=1, sticky=E + W+S)
canvasForCustomers.configure(yscrollcommand=scrollBar.set)
qtyList=[]
for item in allItems:
qtyList.append(Label(frameOfItems,text=item[0]))
actualQtyList.append(item[0])
lb_Qty=ttk.Label(frameOfItems,text="Quantity").grid(row=0,column=1,pady=10)
lb_LineBreak=ttk.Label(frameOfItems,text=" ").grid(row=1,column=0,columnspan=4,pady=12)
##### Adding blank label to attempt alignement
rowNum=2
padyValue=7
for item in range(len(qtyList)):
qtyList[item].grid(row=rowNum,column=4,pady=padyValue)
rowNum=rowNum+1
if rowNum%2==0:
padyValue=7
else:
padyValue=0
root_1.mainloop()

Tkinter is a pretty low-level GUI framework. I'd suggest one of the libraries from here, as they will make your life a whole lot easier.

Related

Scaling grid contents in TkInter with complex structure

I have a tkInter window with a grid in it where each sell is containing several widgets. I want to make the window scalable and make grid cells scale accordingly:
import tkinter as tk
import math
def generate_pod(index, row, col, pod_list):
index = index
# Creating a pod and adding to the grid
pod_frame = tk.Frame(grid_window, borderwidth=0.5, relief="solid")
pod_frame.grid(row=row + 1, column=col)
# Create photoimage
img = tk.PhotoImage(width=160, height=90)
# Create a label diff image
img_label = tk.Label(pod_frame, image=img)
img_label.image = img # Keep a reference to prevent garbage collection
table_button = tk.Label(pod_frame, text=str(index))
score_frame = tk.Frame(pod_frame)
# Create a labels
ssim_label = tk.Label(score_frame, text='Sim: ')
# Movement
move_label = tk.Label(score_frame, text='Movement')
# Brightness
bright_label = tk.Label(score_frame, text='Brigh: ')
# Focus
sharp_label = tk.Label(score_frame, text='Foc: ')
alert_pod = tk.Label(alert_window, text=str(index))
# Add the labels to the pod
img_label.pack(side='top')
score_frame.pack(side='bottom')
table_button.pack(side='bottom')
ssim_label.grid(row=1, column=1)
move_label.grid(row=1, column=2)
bright_label.grid(row=2, column=1)
sharp_label.grid(row=2, column=2)
alert_pod.pack(side='top')
def refresh_pods(grid_rows, grid_cols):
# Destroy any existing widgets in the grid_window
for widget in grid_window.winfo_children():
widget.destroy()
pod_list = []
# Create a grid
for row in range(grid_rows):
for col in range(grid_cols):
# Calculate the index of the current pod
index = row * grid_cols + col
grid_window.rowconfigure(row, weight=1)
grid_window.columnconfigure(col, weight=1)
try:
generate_pod(index, row, col, pod_list)
except Exception as e:
print(e)
# Composing header
header_text = 'Header'
header = tk.Label(grid_window, text=header_text)
header.grid(row=0, column=0, columnspan=grid_cols)
# Schedule the refresh_pods() function to be called again in 2 min
main_window.after(120000, lambda: refresh_pods(grid_rows, grid_cols))
# Getting count of tables and count grid size
table_count = 50
grid_cols = math.floor(math.sqrt(table_count) * 1.2)
grid_rows = math.ceil(table_count/grid_cols)
grid_cols = int(grid_cols)
grid_rows = int(grid_rows)
# Create the main window
main_window = tk.Tk()
main_window.title('CDN snapshots aplha ver')
main_window.eval('tk::PlaceWindow . center')
main_window.resizable(True, True)
# Create a frame for the pods
grid_window = tk.Frame(main_window)
grid_window.pack(side='left', anchor='nw')
alert_window = tk.Frame(main_window)
alert_window.pack(side='right')
# Show the first page of pods
refresh_pods(grid_rows, grid_cols)
# Run the main loop
main_window.mainloop()
I found this snippet in the web that is working as I intend, but I failed to apply it to my code, mostly because all pod generation happens in functions and I didn't manage to pass arguments to labels and vice versa label list out of function
import tkinter as tk
import tkinter.font as tkFont
root = tk.Tk()
label_list = []
font = tkFont.Font(family="Helvetica")
pixel = tk.PhotoImage(width=100, height=1)
for x in range(3):
for y in range(3):
root.rowconfigure(y, weight=1)
root.columnconfigure(x, weight=1)
label_list.append(tk.Label(root, width=40, height=40, image=pixel, relief="groove", compound="center"))
label_list[-1].grid(row=x, column=y, sticky="nsew")
def font_resize(event=None):
for lbl in label_list:
x = lbl.winfo_width()
y = lbl.winfo_height()
root.bind( "<Configure>", font_resize)
root.mainloop()

'MultiColumnListbox' object has no attribute 'curselection'

I am running into an error with my MultiColumnListbox. I am trying to understand how to fix this issue. I am trying to see what is selected in my multicolumn listbox. The mutlicolumn listbox is built using tkinter and has a submit button which should run a function telling me what rows were selected in the multi column listbox. I am receiving this error 'MultiColumnListbox' object has no attribute 'curselection' and cant seem to fix it.
This is my code
import os
import time
import glob
import datetime
from array import *
try:
import Tkinter as tk
import tkFont
import ttk
except ImportError: # Python 3
import tkinter as tk
import tkinter.font as tkFont
import tkinter.ttk as ttk
class MultiColumnListbox(object):
"""use a ttk.TreeView as a multicolumn ListBox"""
def submitFunction():
selection = listbox.curselection()
for k in range(0,len(selection)):
selected = listbox.curselection()[k]
def __init__(self):
self.tree = None
self._setup_widgets()
self._build_tree()
def _setup_widgets(self):
s = """\click on header to sort by that column
to change width of column drag boundary
"""
msg = ttk.Label(wraplength="4i", justify="left", anchor="n",
padding=(10, 2, 10, 6), text=s)
msg.pack(fill='x')
container = ttk.Frame()
container.pack(fill='both', expand=True)
# create a treeview with dual scrollbars
self.tree = ttk.Treeview(columns=car_header, show="headings")
vsb = ttk.Scrollbar(orient="vertical",
command=self.tree.yview)
hsb = ttk.Scrollbar(orient="horizontal",
command=self.tree.xview)
self.tree.configure(yscrollcommand=vsb.set,
xscrollcommand=hsb.set)
self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
vsb.grid(column=1, row=0, sticky='ns', in_=container)
hsb.grid(column=0, row=1, sticky='ew', in_=container)
container.grid_columnconfigure(0, weight=1)
container.grid_rowconfigure(0, weight=1)
def _build_tree(self):
for col in car_header:
self.tree.heading(col, text=col.title(),
command=lambda c=col: sortby(self.tree, c, 0))
# adjust the column's width to the header string
self.tree.column(col,
width=tkFont.Font().measure(col.title()))
for item in car_list:
self.tree.insert('', 'end', values=item)
# adjust column's width if necessary to fit each value
for ix, val in enumerate(item):
col_w = tkFont.Font().measure(val)
if self.tree.column(car_header[ix],width=None)<col_w:
self.tree.column(car_header[ix], width=col_w)
def sortby(tree, col, descending):
"""sort tree contents when a column header is clicked on"""
# grab values to sort
data = [(tree.set(child, col), child) \
for child in tree.get_children('')]
# if the data to be sorted is numeric change to float
#data = change_numeric(data)
# now sort the data in place
data.sort(reverse=descending)
for ix, item in enumerate(data):
tree.move(item[1], '', ix)
# switch the heading so it will sort in the opposite direction
tree.heading(col, command=lambda col=col: sortby(tree, col, \
int(not descending)))
FilesToDeleteName = [];
FilesToDeletePath = [];
FilesToDeleteDate = [];
car_list = [];
car_list.append([])
car_list.append([])
#str1 = input("Enter number of days old: ")
#days = int(str1)
days = 90
count = 0
time_in_secs = time.time() - (days * 24 * 60 * 60)
extf = ['Windows','Program Files', 'Program Files (x86)']
for (root, dirs, files) in os.walk('C:/Users', topdown=True):
dirs[:] = [d for d in dirs if d not in extf]
for filename in files:
Fullname = os.path.join(root,filename)
stat = os.stat(Fullname)
modified = datetime.datetime.fromtimestamp(stat.st_mtime)
if Fullname.endswith('.pcapng') or Fullname.endswith('.evtx') or Fullname.endswith('.png') or Fullname.endswith('.sql') or Fullname.endswith('.etl') or Fullname.endswith('.zip'):
if stat.st_mtime <= time_in_secs:
FilesToDeleteName.append(filename);
FilesToDeletePath.append(Fullname);
FilesToDeleteDate.append(str(modified));
FilesToDelete = [];
for p in range(0,len(FilesToDeletePath)):
STR2 = FilesToDeletePath[p],FilesToDeleteDate[p]
FilesToDelete.append(STR2)
car_list = FilesToDelete
car_header = ["Path ", "Date Modified"]
if __name__ == '__main__':
window = tk.Tk()
window.title("Multicolumn Treeview/Listbox")
listbox = MultiColumnListbox()
def submitFunction():
print(listbox.curselection(self))
window.destroy()
def closeFunction():
window.destroy()
submit = tk.Button(window, text='Submit', command=submitFunction)
submit.pack(side=tk.RIGHT, padx = 20)
close = tk.Button(window, text='Close', command=closeFunction)
close.pack(side=tk.RIGHT)
window.mainloop()
This is the main part of my issue
def submitFunction():
print(listbox.curselection(self))
window.destroy()
I will ultimately be trying to get the index numbers to delete the given file path

why can't i populate my tksheet table row?

I am trying to get a students attendance record set up in python. I have most of it figured out. I am stuck on one section and it is the attendane section. I am trying to use a table format (tksheets) to keep record of students names and their attendance. The issue I am having is working with tksheets. I can't seem to get the information from my DB(SQLite3) to populate the columns. I've also tried tktables, and the pandastables. But again I run into the same issue.
I have considered using the Treeview Widget to populate the columns with the students names, and then use entry boxes to add the attendance. The issue is I have to create each entry box and place it individually. I didn't like this plan. Below is the current code I am using.
If anyone could show me how to get the data from the DB and populate the spreadsheet I am using that be great. Thanks.
def rows(self):
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(1,weight=1)
self.sheet = Sheet(self.aug_tab,
data=[[f'Row{r} Column{c}' for c in range(36)]for r in range(24)],
height=300,
width=900)
self.sheet.enable_bindings(("single",
"drag_select",
"column_drag_and_drop",
"row_drag_and_drop",
"column_select",
"row_select",
"column_width_resize",
"double_click_column_resize",
"row_width_resize",
"column_height_resize",
"arrowkeys",
"row_height_resize",
"double_click_row_resize",
"right_click_popup_menu",
"rc_insert_column",
"rc_delete_column",
"rc_insert_row",
"rc_delete_row",
"copy",
"cut",
"paste",
"delete",
"undo",
"edit_cell"))
self.headers_list = ("Student ID","Ch. First Name","Ch. Last Name","Eng. Name")
self.headers = [f'{c}'for c in self.headers_list]
self.sheet.headers(self.headers)
self.sheet.pack()
print(self.sheet.get_column_data(0,0))
#############DEFINE FUNCTIONS###############################
rows(self)
enter image description here
"""if you want to take data from your database then you must make a main frame and add the button, then make your demo tksheet function as a top level frame, i have made one my own to open my data base, all do you need is change the database in my code with your database. this is my code"""
import tkinter as tk
import datetime as dt
from tkinter import ttk
def open_window1():
from tksheet import Sheet
import tkinter as tk
import sqlite3
conn= sqlite3.connect('toko.db')
c= conn.cursor()
class demo(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.grid_columnconfigure(0, weight = 1)
self.grid_rowconfigure(0, weight = 1)
self.sheet_demo = Sheet(self,
height = 500,
width = 700)
self.sheet_demo.enable_bindings(("single",
"drag_select",
"column_drag_and_drop",
"column_select",
"row_select",
"arrowkeys",
"column_width_resize",
"row_width_resize",
"copy",
"rc_insert_column",
"rc_insert_row"))
self.sheet_demo.grid(row = 0, column= 0, sticky= "nswe")
self.headers= ("id","Produk","Stok","Harga Grosir","Harga Eceran")
self.sheet_demo.headers(self.headers)
c.execute("SELECT * FROM StokDanHarga")
h=len(c.fetchall())
print(h)
self.data =[[f"Row {r} Column {c}" for c in range(3)] for r in range(h)]
self.sheet_demo.data_reference(self.data)
a=c.execute("SELECT * FROM StokDanHarga")
j=0
for row in a:
# i= len(a)
r=j
print(r,j)
self.sheet_demo.set_row_data(r, values = row)
j += 1
app= demo()
app.mainloop()
root= tk.Tk()
root.title("combobox")
root.geometry("400x400")
buttn = ttk.Button(root, text='STOK DAN HARGA', command=open_window1)
buttn.grid(row=0, column=0)
root.mainloop()
"""well you should make a function into your code and a button, while you can insert your student name one by one or copy bulk of yor students name into the sheet, this is my code"""
from tksheet import Sheet
import tkinter as tk
class demo(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.grid_columnconfigure(0, weight = 1)
self.grid_rowconfigure(0, weight = 1)
self.sheet_demo = Sheet(self,
height = 500,
width = 700)
self.sheet_demo.enable_bindings(("single",
"drag_select",
"column_drag_and_drop",
"row_drag_and_drop",
"column_select",
"row_select",
"column_width_resize",
"double_click_column_resize",
"row_width_resize",
"column_height_resize",
"arrowkeys",
"row_height_resize",
"double_click_row_resize",
"right_click_popup_menu",
"rc_insert_column",
"rc_delete_column",
"rc_insert_row",
"rc_delete_row",
"copy",
"cut",
"paste",
"delete",
"undo",
"edit_cell"))
self.sheet_demo.grid(row = 0, column = 0, sticky = "nswe")
self.data = [[f"" for c in range(1)] for r in range(100)]
self.sheet_demo.data_reference(self.data)
def click_this():
for i in (self.sheet_demo.get_column_data(0)):
if i == '':
break
else:
print(i.strip())
self.data = [[f"" for c in range(1)]for r in range(100)]
self.sheet_demo.data_reference(self.data)
button=tk.Button(text=" click this",command= click_this)
button.grid(row= 1, column=0, sticky= "n")
app = demo()
app.mainloop()

Scrollbar is Not getting active in Python TK

I am Creating Multiple tab window using Notebook and in one of tab "Check Box" will created dynamically depending on the values in the Excel . (I am able to read values from Excel and Create the Check Box) . The Number of Check box will be equal to number values in the excel .
In my Excel I have values from 1 to 30 . But i am seeing values till 1 to 11 and other values are down in the UI , But scroll Bar is not active .
Please help me with this .
import tkinter as tk
from dicttoxml import dicttoxml
import xlrd
import GetValueFromExcel
from GetValueFromExcel import ExcelValue
from array import array
from tkinter import *
from tkinter import ttk, Button
from tkinter import *
root = Tk()
CheckBoxSelection=[]
NameOfVariable=[]
KeyName=[]
SelectedCheckbox=[]
dict={}
frame_main = tk.Frame(root)
frame_main.grid(sticky='news')
canvas=tk.Canvas()
class UICreation():
def __init__(self):
print ("I m in __init__")
self.nb=ttk.Notebook(frame_main)
self.page1=ttk.Frame(self.nb)
self.page2=ttk.Frame(self.nb)
def tabcreation(self):
print ("I M in Tab Creation")
self.nb.add(self.page1,text="Select")
canvas = tk.Canvas(self.page1)
canvas.grid(row=0, column=0, sticky="news")
vsb = tk.Scrollbar(self.page1, orient="vertical", command=canvas.yview)
vsb.grid(row=0, column=1, sticky='ns')
canvas.configure(yscrollcommand=vsb.set)
canvas.config(scrollregion=canvas.bbox("all"))
f = tk.Frame(canvas)
canvas.create_window((200, 0), window=f, anchor="n")
self.nb.add(self.page2,text="Add")
self.nb.grid(sticky=N)
print ("I M in checkBox")
ListNumber=len(List_key)
print (ListNumber)
for value in range(0,ListNumber, 1):
NameOfVariable= "checkBox" + str(value)
CheckBoxSelection.append("var"+str(value))
CheckBoxSelection[value]=IntVar()
NameOfVariable = Checkbutton(f, text=str(List_key[value]),variable=CheckBoxSelection[value])
Checkbutton()
NameOfVariable.grid(sticky=NW)
NameOfVariable.cget("text")
KeyName.append(NameOfVariable.cget("text"))
def button(self):
button = Button(frame_main, text="Submit", command=self.OnButtonClick)
button.grid(sticky=NW)
def OnButtonClick(self):
index = 0
SelectedCheckboxValue=[]
for st in (CheckBoxSelection):
if st.get():
SelectedCheckboxKey=KeyName[index]
SelectedCheckboxValue=GetValueFromExcel.row_data_dict[SelectedCheckboxKey]
index+=1
dict={
"Properties": {"id": "ConnectJetSerialNumber"+SelectedCheckboxKey,"value":SelectedCheckboxValue[0],"PrinterName":SelectedCheckboxValue[1],"PrinterName2":SelectedCheckboxValue[2]}
}
print(dict)
xml = dicttoxml(dict, custom_root='test', attr_type=False)
file=open(r"C:\SmallVille\SmallVilleAutoConfigGUI\Selected.xml","a")
file.write(str(xml))
else:
index+=1
if __name__ == '__main__':
ui = UICreation()
ev = GetValueFromExcel.ExcelValue()
t=ev.readExcelValue()
print("I am before print t")
print(t)
print("I am before list")
List_key= list(t.keys())
print (List_key)
ui.tabcreation()
ui.button()
root.mainloop()
UI Screen Shoot also attached

Python TKInter how do I replace data in my frames?

I'm having a major issue with my code below. So here's what I'm trying to do.
The user enters certain inputs into the entry fields and the program calculates and displays a corresponding image (loaded in the frame champFrame) and it's description (in spellFrame).
What I want is to replace this image and text every time I click on the Calculate! button so that it shows me a new image and new description based on my new inputs.
However, in its current state, when I enter new input and click the Calculate! button, it just adds the new image below the old one and the old one is still there.
How do I change my code around so that I can replace these old values?
I have heard of using the pack_forget() method but it only hides the previous image, does not remove it so I can replace it with a new one.
from Tkinter import *
from PIL import ImageTk
from Calculation import getHighestScore
from ImageHandler import *
import json
import urllib2
top = Tk()
top.title("LOLSpellEfficiency")
top.geometry("600x600")
def loadInputFields(frame):
AP_Label = Label(frame, text="AP")
AD_Label = Label(frame, text="AD")
CDR_Label = Label(frame, text="CDR")
AP_Label.grid(row=0, column=0)
AD_Label.grid(row=1, column=0)
CDR_Label.grid(row=2, column=0)
AP_Entry = Entry(frame)
AD_Entry = Entry(frame)
CDR_Entry = Entry(frame)
AP_Entry.grid(row=0, column=1)
AP_Entry.insert(0, "0")
AD_Entry.grid(row=1, column=1)
AD_Entry.insert(0, "0")
CDR_Entry.grid(row=2, column=1)
CDR_Entry.insert(0, "0")
return [AP_Entry, AD_Entry, CDR_Entry]
def loadButton(frame, entries):
Enter_Button = Button(frame, text="Calculate!", command = lambda: executeProgram(entries))
Enter_Button.pack(side=TOP)
def executeProgram(entries):
AP = float(entries[0].get())
AD = float(entries[1].get())
CDR = float(entries[2].get())
data = getChampionData()
result = getHighestScore(data, AP, AD, CDR)
champPhoto = ImageTk.PhotoImage(getChampionImage(result[0]))
champLabel = Label(championFrame, image=champPhoto)
champLabel.image = champPhoto
champLabel.pack(side = TOP)
champName = Label(championFrame, text = "Champion: " + result[0])
champName.pack(side = BOTTOM)
spellPhoto = ImageTk.PhotoImage(getSpellImage(result[2]))
spellLabel = Label(spellFrame, image=spellPhoto)
spellLabel.image = spellPhoto
spellText = Text(spellFrame, wrap=WORD)
spellText.insert(INSERT, "Spell: " + result[1] + "\n")
spellText.insert(INSERT, "Spell description: " + result[3] + "\n")
spellLabel.pack(side=TOP)
spellText.pack(side=BOTTOM)
championFrame.pack()
spellFrame.pack()
def getChampionData():
URL = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?champData=all&api_key=8e8904b4-c112-4b0f-bd1e-641649d9e569"
return json.load(urllib2.urlopen(URL))
inputFrame = Frame(top)
inputFrame.pack()
buttonFrame = Frame(top)
buttonFrame.pack()
championFrame = Frame(top)
spellFrame = Frame(top)
championFrame.pack()
spellFrame.pack()
entries = loadInputFields(inputFrame)
loadButton(buttonFrame, entries)
top.mainloop()
Do not create widgets inside of executeProgram. Instead, create them in your main application, and simply change the widgets inside executeProgram.
All widgets have a configure method which lets you change all of the attributes of that widget. For example, to change the image on a label you would do something like this:
champPhoto = ImageTk.PhotoImage(getChampionImage(result[0]))
champLabel.configure(image=champPhoto)
champLabel.image = champPhoto

Categories