Print from Tk Listbox on selection - python-3.x

I am able to select items from my list but once I click the item I am not able to print the contents back to the terminal. I am also trying to figure out how to close the prompt once the user makes a selection. Any help would be greatly appreciated.
window.title('UTC Time Selection')
# for scrolling vertically
yscrollbar = Scrollbar(window)
yscrollbar.pack(side = RIGHT, fill = Y)
label = Label(window,
text = "Select the UTC Time for Scanning to Start : ",
font = ("Times New Roman", 12),
padx = 10, pady = 10)
label.pack()
list = Listbox(window, selectmode = "single",
yscrollcommand = yscrollbar.set)
# Widget expands horizontally and
# vertically by assigning both to
# fill option
list.pack(padx = 10, pady = 10,
expand = YES, fill = "both")
x =["0000", "0100", "0200", "0300", "0400",
"0500", "0600", "0700", "0800", "0900",
"1000", "1100", "1200", "1300", "1400",
"1500", "1600", "1700", "1800", "1900",
"2000", "2100", "2200", "2300"]
for each_item in range(len(x)):
list.insert(END, x[each_item])
list.itemconfig(each_item, bg = "white")
# Attach listbox to vertical scrollbar
yscrollbar.config(command = list.yview)
Button(window, text="Save & Exit", command=window.destroy).pack()
window.mainloop()
the_response = list.get(list.curselection())
print (the_response)

Related

Tkinter How to make listbox appear over a frame

making an F1 application where users can type in a driver from the current grid [supported via autofill/suggestions], and then API fetches relevant stats
The issue I'm having is that I want the listbox to appear over another frame (called left_frame). However, what this does is that the listbox goes under left_frame , and not over it. Any thoughts of how to make it appear over the frame?
some approaches that I tried:
used .lift(), but .lift() only seems to work when it's relative to objects in the same frame
since I currently use .grid and placed the listbox in the root frame, I initially tried to put it in top_frame, but it then expands the top_frame. Since I have positioned all frames using .place(), I don't think I can use propagate(False) (I tried it , didn't work)
Here's a picture of the issues
Here's my code so far:
#import necessary modules
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image
from tkinter import messagebox
import requests
import json
#set up main window components
root = Tk()
root.title("F1 Desktop Application")
root.geometry("500x600")
root.configure(bg="white")
#since same directory, can just use filename
root.iconbitmap("formula1_logo.ico")
#images
#creating canvas for image to go into
#canvas_f1_logo = Canvas(top_frame, width = 5, height = 5)
#canvas.grid(row = 0, column = 1)
#acquire image
#formula1_logo = ImageTk.PhotoImage(Image.open("formula1_logo.png"))
#resize image
#resized_formula1_logo = formula1_logo.resize((3,3), Image.ANTIALIAS)
#new_formula1_logo = ImageTK.PhotoImage(resized_formula1_logo)
#canvas.create_image(5,5, anchor = NW, image = new_formula1_logo)
#functions
#generate 2022 drivers-list [can scale to drivers-list by changing the]
drivers_list_request = requests.get("http://ergast.com/api/f1/2022/drivers.json")
#initialize empty-list
drivers_list = []
drivers_list_object = json.loads(drivers_list_request.content)
for elements in drivers_list_object["MRData"]["DriverTable"]["Drivers"]:
drivers_list.append(elements["givenName"] + " " + elements["familyName"])
#set up frames [main frames, can put frames within frames if needed]
#frame for search bar + magnifying glass
top_frame = LabelFrame(root, padx = 80, pady = 15)
top_frame.place(relx = 0.5, rely = 0.2, anchor = CENTER)
header_label = Label(top_frame, text = "F1 2022 Drivers App", pady = 20, font = ("Arial bold",14))
header_label.grid(row = 0, column = 0, pady = 2 )
search_button = Button(top_frame, text = "search", padx = 2, pady = 2)
search_button.grid(row = 1, column = 1)
# Update the Entry widget with the selected item in list
def check(e):
v= entry.get()
if v=='':
hide_button(menu)
else:
data=[]
for item in drivers_list:
if v.lower() in item.lower():
data.append(item)
update(data)
show_button(menu)
def update(data):
# Clear the Combobox
menu.delete(0, END)
# Add values to the combobox
for value in data:
menu.insert(END,value)
def fillout(event):
try:
entry.delete(0,END)
entry.insert(0,menu.get(menu.curselection()))
#handle a complete deletion of entry-box via cursor double tap
except:
pass
def hide_button(widget):
widget.grid_remove()
def show_button(widget):
widget.grid()
# Create an Entry widget
entry= Entry(top_frame)
entry.grid(row = 1, column = 0)
entry.bind('<KeyRelease>',check)
# Create a Listbox widget to display the list of items
menu= Listbox(root)
menu.grid(row = 2, column = 0, padx = 165, pady = 165)
menu.bind("<<ListboxSelect>>",fillout)
menu.lift()
# Add values to our combobox
hide_button(menu)
left_frame = LabelFrame(root, padx = 30, pady = 30)
left_frame.place(relx = 0.24, rely = 0.5, anchor = CENTER)
bottom_left_frame = LabelFrame(root, padx = 30, pady = 30)
bottom_left_frame.place(relx = 0.24, rely = 0.82, anchor = CENTER)
bottom_right_frame = LabelFrame(root, padx = 30, pady = 30)
bottom_right_frame.place(relx = 0.6, rely = 0.82)
basic_info = Label(left_frame, text = "Basic Info ", font = ("Arial bold",14))
basic_info.grid(row = 0, column = 0, pady = 3)
full_name = Label(left_frame, text = "Full Name : ")
full_name.grid(row = 1, column = 0, pady = 2)
driver_code = Label(left_frame, text = "Driver Code : ")
driver_code.grid(row = 2, column = 0, pady = 2)
nationality = Label(left_frame, text = "Nationality : ")
nationality.grid(row = 3, column = 0, pady = 2)
F1_career = Label(bottom_left_frame, text = "F1 Career ", font = ("Arial bold",14))
F1_career.grid(row = 0, column = 0, pady = 3)
wins = Label(bottom_left_frame, text = "Wins :")
wins.grid(row = 1, column = 0, pady = 2)
poles = Label(bottom_left_frame, text = "Poles :")
poles.grid(row = 2, column = 0, pady = 2)
drivers_championships = Label(bottom_left_frame, text = "Championships :")
drivers_championships.grid(row = 3, column = 0 , pady = 2)
F1_22_stats = Label(bottom_right_frame, text = "F1 22 Stats", font = ("Arial bold",14))
F1_22_stats.grid(row = 0, column = 0, pady = 3)
root.mainloop()
would appreciate the help!

Getting a list variable out of Tkinter window

I am trying to get a list out of Tkinter and I want to add a Y-axis scroll bar to the list box but don't know-how. My code is as follows:
window = Tk()
window.title('Select Multiple Industries')
window.geometry('400x800')
def showindowelected():
industries = []
iname = lb.curselection()
for i in iname:
op = lb.get(i)
industries.append(op)
print (industries)
window.destroy()
#for val in industries:
#print(val)
show = Label(window, text = "Select Multiple Industries", font = ("Times", 14), padx = 10, pady = 10)
show.pack()
lb = Listbox(window, selectmode = "multiple")
lb.pack(padx = 10, pady = 10, expand = YES, fill = "both")
x = ["Brewing","Papermills","Cheese Manufacturing","Steel Mill", "Salt Making"]
for item in range(len(x)):
lb.insert(END, x[item])
lb.itemconfig(item, bg = "whitesmoke" if item % 2 == 0 else "silver")
Button(window, text=" Select > ", command=showindowelected, bg='green', fg='white').pack()
window.mainloop()
Once the window is destroyed, I want the selected variables stored in a list.

I have created an Entry Widget and placed it in the grid but it doesn't show

I'm creating a front end for a customer access and on one of my pages, the entry widget that I want to place next to the label doesn't show, I don't get any errors.
I've placed it on a grid and moved it around, I have made sure nothing else is in it's part of the grid
from tkinter import *
from tkinter import ttk
newCustomerPage = Tk()
newCustomerPage.geometry('400x172') #define the size of the window
newCustomerPage.overrideredirect(True) #removes the bar at the top of the window
windowWidth = newCustomerPage.winfo_reqwidth() #Place the window in the middle of the page
windowHeight = newCustomerPage.winfo_reqheight()
positionRight = int(newCustomerPage.winfo_screenwidth()/2.3 - windowWidth/2)
positionDown = int(newCustomerPage.winfo_screenheight()/3 - windowHeight/2)
newCustomerPage.geometry("+{}+{}".format(positionRight, positionDown))
print("New Customer Page set")
customerPageLabel = Label(newCustomerPage, text = "New Customer", font = ("Calibri", 25), padx = 110)#.pack(side = TOP, pady = 1)
customerPageLabel.grid(row = 0, column = 0)
newCustNameLabel = Label(newCustomerPage, text = 'Given Name:', font = ("Calibri", 12))#.pack(side = TOP, pady = 1)
newCustNameLabel.grid(row = 1, column = 0)
newCustNameEntry = Entry(newCustomerPage, width = 10)
newCustNameEntry.grid(row = 1, column = 1)
close = ttk.Button(newCustomerPage, text = 'Close', width = 20, command = newCustomerPage.destroy)#.pack(side = TOP, pady = 8)
close.grid(row = 2, column = 0)
The page opens and displays "New Customer" then directly below that in the middle of the page displays "Given Name:" then directly below that displays the "close" button which functions fine, I want the entry box to display to the right of 'newCustNameLabel' but it doesn't
From the docs:
padx: The amount specifies how much horizontal external padding to leave on each side of the slave(s), in screen units.
So by setting padx=100 in your grid column #0, you applied padding for 100px on both sides, which pushes the Entry widget off screen.
Instead of using padx, what you should do is to set the columnspan of customerPageLabel so it can span over more than 1 column:
customerPageLabel = Label(newCustomerPage, text = "New Customer", font = ("Calibri", 25))
customerPageLabel.grid(row = 0, column = 0, columnspan=2)
And if you want the columns to occupy all the remaining space, set a weight to the columns:
newCustomerPage.columnconfigure(0,weight=1)
newCustomerPage.columnconfigure(1,weight=1)

How to set a default cursor selection in a Listbox py3

this is my code, and it works fine When the program starts there is no selection in the listbox and I want to set a default selection in the listbox, for the case when a selection is not made by the user. any help, please!
### frame_3 widgets.
frame_3 = Frame(frame_2)
label_1a = Label(frame_3, relief = 'solid', width = 17)
label_1a.configure(text = "Start of Period month")
### listbow_1 and static attributes.
listbox_1 = Listbox(frame_3, exportselection=0, width = 12, height = 12)
for item in ['January','Febuary','March',
'April','May','June',
'July','August','September',
'October','November','December']:
listbox_1.insert(END,item)
label_2a = Label(frame_3, relief = 'groove', width = 10)
label_2a.configure(text = "Start day")
entry_1 = Entry(frame_3, width = 2)
### geometry frame_3
label_1a.grid (column = 0, row = 2)
frame_3.grid (column = 0, row = 2)
listbox_1.grid(column = 0, row = 3)
label_2a.grid (column = 0, row = 5)
entry_1.grid (column = 1, row = 5)
You can use listbox.selection_set(0) to select first item on list
More in documentation: Listbox.selection_set
Full example
import tkinter as tk
def test():
# here you can get selected element
print('previous:', listbox.get('active'))
print(' current:', listbox.get(listbox.curselection()))
# --- main ---
root = tk.Tk()
listbox = tk.Listbox(root)
listbox.pack()
listbox.insert(1, 'Hello 1')
listbox.insert(2, 'Hello 2')
listbox.insert(3, 'Hello 3')
listbox.insert(4, 'Hello 4')
listbox.selection_set(0)
button = tk.Button(root, text="Test", command=test)
button.pack()

How to print the same text multiple times(5 times) in tkinter/GUI?

from tkinter import *
root=Tk()
textbox=Text(root)
textbox.pack()
button1=Button(root, text='Output Name', command=lambda : print('Hello'))
button1.pack()
def redirector(inputStr):
textbox.insert(INSERT, inputStr)
sys.stdout.write = redirector
root.mainloop()
This is my code with out a timer to do it five times.
This seems a little bit like homework, so lets try to get you on the right track over outright providing the code to accomplish this.
You're going to want to create a loop that performs your code a certain number of times. Let's say we just want to output a certain string 5 times. As an example, here's some really simple code:
def testPrint():
print('I am text!')
for i in range(5):
testPrint()
This will create a function called testPrint() that prints text "I am Text!", then run that function 5 times in a loop. If you can apply this to the section of code you need to run 5 times, it should solve the problem you are facing.
This worked for me. It creates a table using the .messagebox module. You can enter your name into the entry label. Then, when you click the button it returns "Hello (name)".
from tkinter import *
from tkinter.messagebox import *
master = Tk()
label1 = Label(master, text = 'Name:', relief = 'groove', width = 19)
entry1 = Entry(master, relief = 'groove', width = 20)
blank1 = Entry(master, relief = 'groove', width = 20)
def show_answer():
a = entry1.get()
b = "Hello",a
blank1.insert(0, b)
button1 = Button(master, text = 'Output Name', relief = 'groove', width = 20, command =show_answer)
#Geometry
label1.grid( row = 1, column = 1, padx = 10 )
entry1.grid( row = 1, column = 2, padx = 10 )
blank1.grid( row = 1, column = 3, padx = 10 )
button1.grid( row = 2, column = 2, columnspan = 2)
#Static Properties
master.title('Hello')

Resources