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
Related
text not properly align in pack. I want the text to be on top and pack on bottom but every time I try to align the "Enter Password Length" disappear
from tkinter import Button, Entry , Label, Tk
from tkinter.constants import END
import pyperclip
import string
password_chars = string.ascii_letters + string.digits + string.punctuation
class gui:
def __init__(self):
self.window = Tk()
self.window.title("Password Generator")
self.window.geometry("300x300")
# Label Frame
label_title = Label(text="Password Generator", fg="#800000",font=("Inter", 15, "bold"))
label_title.pack(pady=15)
self.label = Label(
self.window, text="Enter Password Length",font=("Inter"))
self.label.pack(pady=20,)
# Entry box for number of characters
self.length_entry_box = Entry(self.label, width=24,)
self.length_entry_box.pack(padx=10, pady=15)
if __name__ == '__main__':
gui().window.mainloop()
The problem is you give the master option in the entry as self.label this should be self.window.
master=self.label(or the first parameter) means entry should inside self.label.
from tkinter import Button, Entry, Label, Tk
from tkinter.constants import END
import pyperclip
import string
password_chars = string.ascii_letters + string.digits + string.punctuation
class gui:
def __init__(self):
self.window = Tk()
self.window.title("Password Generator")
self.window.geometry("300x300")
# Label Frame
label_title = Label(text="Password Generator", fg="#800000",font=("Inter", 15, "bold"))
label_title.pack(pady=15)
self.label = Label(
self.window, text="Enter Password Length",font=("Inter"))
self.label.pack(pady=20,)
# Entry box for number of characters
self.length_entry_box = Entry(self.window, width=24,) # self.label changes to self.window.
self.length_entry_box.pack(padx=10, pady=15)
if __name__ == '__main__':
gui().window.mainloop()
In line 23. Removed object self.label,
from tkinter import Button, Entry , Label, Tk
from tkinter.constants import END
import pyperclip
import string
password_chars = string.ascii_letters + string.digits + string.punctuation
class gui:
def __init__(self):
self.window = Tk()
self.window.title("Password Generator")
self.window.geometry("300x300")
# Label Frame
label_title = Label(text="Password Generator", fg="#800000",font=("Inter", 15, "bold"))
label_title.pack(pady=15)
self.label = Label(
self.window, text="Enter Password Length",font=("Inter"))
self.label.pack(pady=20,)
# Entry box for number of characters
self.length_entry_box = Entry(width=24)
self.length_entry_box.pack(padx=10, pady=15)
if __name__ == '__main__':
gui().window.mainloop()
Output:
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
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.
I have this render_gui function in Python.
def render_gui():
global root
global prev_key
global listbox, label1, entry1
prev_key = 0
root = tk.Tk()
root.title('Server Chat Application')
scroll = Scrollbar(root)
scroll.pack(side = "right" , fill= "y")
listbox = Listbox(root, width=80, height=30)
listbox.grid(row=1,column=1, columnspan=5,rowspan=3)
scroll.config(command = listbox.yview)
label1 = ttk.Label(root, text='Message Entry Box : ')
label1.grid(row=4,column=1)
entry1 = ttk.Entry(root, width=60)
entry1.grid(row=4, column=2)
root.geometry('490x520')
#print('before main loop')
root.bind('<KeyPress>', onKeyPress)
#print('after main loop')
root.mainloop()
It was throwing an error after I added the scrollbar thing. How will I encorporate a vertical and horizontal scrollbar in my listbox. Thanks.
UPDATE:
Below is the complete code. I have edited it and omit the pack thing replace it with grid function but the scrollbar wasn't showing. How am I gonna deal with this?
import os
import signal
import socket
import time
import threading
import keyboard
from threading import Thread
import tkinter as tk
from tkinter import ttk
from tkinter import *
import webbrowser
def onKeyPress(event):
global prev_key
global root
global listbox, label1, entry1
if(event.keycode == 13):
print(Entry.get(entry1))
msg = Entry.get(entry1)
if len(str.encode(msg)) > 0:
client.send(str.encode("\nserver > " + msg))
listbox.insert(END, "server > " + msg)
entry1.delete(0,END)
if(event.keycode == 88) and (prev_key == 17):
root.destroy()
try:
raise client.send(str.encode("***Server has been shutdowned***"))
except:
print ("You are not yet connected to any client to send shutdown notice.")
sys.exit()
os.kill(os.getpid(), signal.SIGUSR1)
prev_key = event.keycode
def render_gui():
global root
global prev_key
global listbox, label1, entry1
prev_key = 0
root = tk.Tk()
root.title('Server Chat Application')
scroll = Scrollbar(root)
#scroll.pack(side = "right" , fill= "y")
scroll.grid(row=0, column=10, rowspan=10, sticky='ns')
listbox = Listbox(root, width=80, height=30)
listbox.grid(row=1,column=1, columnspan=5,rowspan=3)
scroll.config(command = listbox.yview)
listbox.config(yscrollcommand=scroll.set)
label1 = ttk.Label(root, text='Message Entry Box : ')
label1.grid(row=4,column=1)
entry1 = ttk.Entry(root, width=60)
entry1.grid(row=4, column=2)
root.geometry('490x520')
#print('before main loop')
root.bind('<KeyPress>', onKeyPress)
#print('after main loop')
root.mainloop()
if __name__ == "__main__":
Thread(target= render_gui).start()
from tkinter import *
import sys,math,random,datetime,os,time
import tkinter.messagebox
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
from time import gmtime, strftime
import xlsxwriter
export = "Excel"
current_time = strftime("%m-%d-%Y %H:%M", gmtime())
root = Tk()
e1 = Entry()
e1.insert(10, "First Name")
e2 = Entry()
e2.insert(10, "Last Name")
Here is where I am trying to format variable to become string.
fullname = "%s %s" % (e1, e2)
title = ["Titan Tech", "Caleb Fahlgren made this!", "Python is life!", "FIRST Robotics!","Doesn't this make your life easier?"]
title = (random.choice(title))
root.title(title)
root.geometry("640x600")
#Submit Button
def Submit():
submit = tkinter.messagebox.askquestion("Submit Entry", "Are you sure you want to submit?")
if submit == "yes":
Xlsx program.
workbook = xlsxwriter.Workbook('TitanTechSummary.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})
worksheet.write('A1', 'Name:',bold)
This is where I am trying to write the players input for name. Or the tkinter Entry(). But I keep getting like a weird decimal number when I look at the excel document. I keep getting this in the B1 field '.140041879004720 .140041884602944'
worksheet.write_string('B1',fullname, bold)
worksheet.write('C1', 'Date:',bold)
I also want to do the same thing with the date.
worksheet.write('D1', 'Date')
workbook.close()
userconfirm = tkinter.messagebox.showinfo("Save","Your entry has been saved to an " + export + " document!")
def keypress(event):
if event.keysym == 'Escape':
root.destroy()
def Quit():
quitask = tkinter.messagebox.askquestion("Quit", "Are you sure you want to quit?")
if quitask == "yes":
root.destroy()
def Insert():
filen = askopenfilename()
filen1 = tkinter.messagebox.showinfo("Saved", "If you opened a picture we saved it!")
firstname = Label(root, text="First Name",font=("Helvetica", 12),fg="green")
lastname = Label(root, text="Last Name",font=("Helvetica", 12),fg="green")
time = Label(root, text=current_time, font=("Helvetica", 12),fg="black")
TextArea = Text()
ScrollBar = Scrollbar(root)
ScrollBar.config(command=TextArea.yview)
TextArea.config(yscrollcommand=ScrollBar.set)
ScrollBar.pack(side=RIGHT, fill=Y)
Submit = Button(root, fg="white", bg="green", text="Submit", width=50, command=Submit, activebackground="yellow")
Quit = Button(root, fg="white", bg="green", text="Quit", width=50, command=Quit,activebackground="yellow")
Insert = Button(root,fg="white", bg="green", text="Insert Images", width=50, command=Insert,activebackground="yellow")
root.bind_all('<Key>', keypress)
firstname.pack()
e1.pack()
lastname.pack()
e2.pack()
time.pack()
TextArea.pack(expand=YES, fill=BOTH)
Insert.pack()
Submit.pack()
Quit.pack()
mainloop()
The problem is this line of code:
fullname = "%s %s" % (e1, e2)
e1 and e2 are entry widgets. Their string representation (ie: if you do str(e1)) is going to be "a weird decimal number".
You need to be calling the get() method of the widget to get the contents:
fullname = "%s %s" % (e1.get(), e2.get())