I have this table in tkinter. However, I want to have only one button in each row with four text fields. (I currently have four buttons in each row.)
Basically, I want to connect these four buttons to one button in a row. How can I do this?
from tkinter import *
class Table:
def __init__(self,root):
# code for creating table
for i in range(total_rows):
for j in range(total_columns):
self.e = Button(root, width=20,text = lst[i][j])
self.e.grid(row=i, column=j)
# take the data
lst = [(1,'Raj','Mumbai',19),
(2,'Aaryan','Pune',18),
(3,'Vaishnavi','Mumbai',20),
(4,'Rachna','Mumbai',21),
(5,'Shubham','Delhi',21)]
# find total number of rows and
# columns in list
total_rows = len(lst)
total_columns = len(lst[0])
# create root window
root = Tk()
t = Table(root)
root.mainloop()
I've modified your code to include a Toplevel window called 'work' that gives access to the super buttons. The quantity of buttons is determined by the number of rows in table.
Each button is connected to another Toplevel window called 'edit'.
'Edit' contains Label, Entry and Button objects. The quantity is determined by the number of columns in table.
All windows are resizable with 'work' and 'edit' windows accessible via F1 key.
Escape key will close 'top' table via messagebox.
Ok this is the latest version.
I've divided the project into two python files, a data file called 'Datafile.py' and code called "Records.py'.
'Datafile.py' must be saved separately from 'Records.py.
Records code is completely configurable by changing table data in Datafile.py
Changing table data by adding or modifying columns and/or rows will configure the main program. The table, work and edit windows are determined by the row and columns in Datafile.py
SAVE THIS AS 'Datafile.py'
import time
timedate = time.localtime()
year = timedate.tm_year
indice = [ "gender", "name", "location", "age", "birth"]
table = [
["Male", "Raj", "Mumbai", 19, year-19],
["Male", "Aaryan", "Pune", 18, year-18],
["Female", "Vaishnavi","Mumbai", 20, year-20],
["Female", "Rachna", "Mumbai", 21, year-21],
["Male", "Shubham", "Delhi", 21, year-21],
["Male", "Roger", "New York", 17, year-17],
["Male", "David", "Sydney", 53, year-53],
["Female", "Jennifer", "London", 42, year-42]]
Here is the main program 'Records.py'.
SAVE AS 'Records.py'
import tkinter as tk
from tkinter import messagebox
from Datafile import timedate, indice, table
class Table:
def __init__(self, master):
self.master = root
self.master.title("Table")
# create table of buttons in self.store
self.rows = len(table)
self.columns = len(table[0])
# number of rows and columns
self.store = []
for r in range(self.rows):
self.store.append([])
for c in range(self.columns):
e = tk.Label(
self.master, width = 20, bd = 1,
relief = "raised", text = table[r][c])
e.grid(row = r, column = c, sticky = tk.NSEW)
self.flexx(self.master, r = r, c = c)
self.store[r].append(e) # all table buttons stored in list
self.master.geometry(f"{self.columns*100}x{self.rows*26}")
self.master.update()
# create toplevel widget for buttons
self.work = tk.Toplevel(self.master)
self.work.transient(self.master)
self.work.withdraw()
self.work.title("Individual Selector")
# populate toplevel widget with the Super buttons
# make buttons resizable
for r in range(self.rows):
e = tk.Button(
self.work, text = f"{table[r][1]}", bd = 1,
command = self.redirect(self.access, r))
e.grid(row=r, column=0, sticky = tk.NSEW)
self.flexx(self.work, r = r)
# Table edit window
self.edit = tk.Toplevel(self.master)
self.edit.transient(self.master)
self.edit.withdraw()
self.edit.title("Table Editor")
self.labelframe = tk.LabelFrame(self.edit, labelanchor = tk.N, text = "Name")
self.labelframe.grid(row = 0, column = 0, sticky = tk.NSEW)
self.flexx(self.edit)
# place entry tools here
self.data = []
for c in range(self.columns):
l = tk.Label(self.labelframe, text = f"{indice[c]}")
l.grid(row = c, column = 0, sticky = tk.NSEW)
e = tk.Entry(self.labelframe)
e.grid(row = c, column = 1, sticky = tk.NSEW)
self.data.append(e)
b = tk.Button(
self.labelframe, text = "Enter", bd = 1,
command = self.redirect(self.change, c))
b.grid(row = c, column = 2, sticky = tk.NSEW)
self.flexx(self.labelframe, r = c, c = 1)
# wire up master and work widgets
for a, b in [(self.master, self.closer),
(self.work, self.opener),
(self.edit, self.editor)]:
a.protocol('WM_DELETE_WINDOW', b)
a.bind("<KeyRelease-Escape>", b)
# Keys to work widget
self.master.bind("<F1>", self.opener)
self.work.bind("<F1>", self.opener)
self.edit.bind("<F1>", self.editor)
def redirect(self, f, *args):
return lambda: f(*args)
def flexx(self, m, r = 0, c = 0, rw = 1, cw = 1):
m.rowconfigure( r, weight = rw )
m.columnconfigure( c, weight = cw )
def change(self, c):
e = self.data[c]
self.store[self.currentRow][c]["text"] = e.get()
table[self.currentRow][c] = e.get()
def closer(self, ev = None):
if messagebox.askquestion(title = "Quit", message = "Confirm",
detail = "Close program?") == "yes":
self.master.destroy()
def opens( self, o, m ):
"""Toggle switch for toplevel"""
if o.winfo_viewable( ):
o.withdraw( )
m.focus_set( )
else:
o.focus_set( )
o.deiconify()
def position(self, o):
x = int(o.winfo_x() + o.winfo_width() + 5)
y = int(o.winfo_y() + o.winfo_height() / 2)
return x, y
def opener(self, ev = None):
x, y = self.position( self.master)
self.work.geometry(f"190x{26*self.rows}+{x}+{y}")
self.opens(self.work, self.master)
def editor(self, ev = None):
x, y = self.position( self.work)
self.edit.geometry(f"213x{26*self.columns}+{x}+{y}")
self.opens(self.edit, self.work)
def access(self, *args):
self.currentRow = r = args[0]
self.labelframe["text"] = f"{table[r][1]}"
for i,e in enumerate(self.data):
e.delete(0, "end")
e.insert(0, table[r][i])
self.editor()
if __name__ == "__main__":
root = tk.Tk()
top = Table(root)
root.mainloop()
Related
new to Tkinter... I am trying to make a mini app in Tkinter where the user selects the state of a medical facility in one combobox and the specific name of a facility in a second combobox from that state. Right now, I've been able to work get my dataframe to filter to the values selected in the state (first combobox), but not the facility too. I only want facilities for the previously selected state to appear in the second combobox. Currently all of the facilities appear in the second combobox, regardless of the state selected in combobox 1. I know my code is wrong, but I'm trying to show that I'm making an attempt here.
Just as an example, if I selected 'oh' for the state in combobox 1, I would only want 'acme facility' and '123 healthcare' to appear in combobox 2. From there, if I selected '123 healthcare', my dataframe would just consist of facilities in Ohio named '123 healthcare.'
Basically, if I were just working in pandas (but I need to do it in Tkinter) and my IDE command, I would want it to do this:
newdf = df.loc[((df['state'] == combobox1value) & (df['provname'] == combobox2value))]
Any help is appreciated.
import pandas as pd
from tkinter import ttk
import numpy as np
from tkinter import Tk
import tkinter as tk
# function to get unique values
def unique(list1):
x = np.array(list1)
print(np.unique(x))
def on_click():
val = n.get()
if val == 'all':
print(df)
else:
df2 = df[ df['state'] == val ]
print(df2)
def on_click2():
val = n2.get()
if val == 'all':
print(df)
else:
df2 = df[ df['provname'] == val ]
print(df2)
df2.to_excel('test.xlsx')
df = pd.DataFrame({
'logdate': ['1/1/2020','1/2/2022', '1/3/2022', '3/3/2021','5/13/2021','10/11/2019','1/5/2020'],
'state': ['oh','oh', 'oh', 'ar','mi','ma','ms'],
'provname': ['acme facility','123 healthcare', '123 healthcare','basic clinic','healthcare solutions','best clinic','one stop clinic'],
})
values = ['all'] + list(df['state'].unique())
dfx = df.loc[((df['state'] == 'oh') & (df['provname'] == '123 healthcare'))]
print(dfx)
# Creating tkinter window and set dimensions
window = tk.Tk()
window.title('Combobox')
window.geometry('500x250')
# label text for title
ttk.Label(window, text = "Main Menu",
background = 'cyan', foreground ="black",
font = ("Times New Roman", 15)).grid(row = 0, column = 1)
#FILTER STATE - PART 1
# Set label
ttk.Label(window, text = "Select the State :",
font = ("Times New Roman", 12)).grid(column = 0,
row = 5, padx = 6, pady = 25)
# Create Combobox
n = tk.StringVar()
state = ttk.Combobox(window, width = 27, textvariable = n)
# Adding combobox drop down list
state['values'] = list(df['state'].unique())
state.grid(column = 1, row = 5)
state.current()
#FILTER FACILITY - PART 2
# Set label
ttk.Label(window, text = "Select the Facility :",
font = ("Times New Roman", 12)).grid(column = 0,
row = 6, padx = 6, pady = 25)
ttk.Button(window, text = "OK", command=on_click).grid(column = 2,
row = 6, padx = 5, pady = 25)
# Create Combobox
n2 = tk.StringVar()
prov = ttk.Combobox(window, width = 27, textvariable = n2)
# Adding combobox drop down list
prov['values'] = list(df['provname'].unique())
prov.grid(column = 1, row = 6)
prov.current()
window.mainloop()
You need to update the values in your second combobox when you select your state. To do this, you need to bind the "<<ComboboxSelected>>" event in the first combobox with a function that changes the second combobox values.
# Function for when first combobx selected
def state_selected(event):
state_value = state.get()
facilities = list(df.loc[df['state']==state_value]['provname'].unique())
if facilities:
prov['values']=facilities
else:
prov['values']=""
# Bind for when your first combobox is selected
state.bind("<<ComboboxSelected>>", state_selected)
Inserting the above snippet in your script gives:
import pandas as pd
from tkinter import ttk
import numpy as np
from tkinter import Tk
import tkinter as tk
# function to get unique values
def unique(list1):
x = np.array(list1)
print(np.unique(x))
def on_click():
val = n.get()
if val == 'all':
print(df)
else:
df2 = df[ df['state'] == val ]
print(df2)
def on_click2():
val = n2.get()
if val == 'all':
print(df)
else:
df2 = df[ df['provname'] == val ]
print(df2)
df2.to_excel('test.xlsx')
df = pd.DataFrame({
'logdate': ['1/1/2020','1/2/2022', '1/3/2022', '3/3/2021','5/13/2021','10/11/2019','1/5/2020'],
'state': ['oh','oh', 'oh', 'ar','mi','ma','ms'],
'provname': ['acme facility','123 healthcare', '123 healthcare','basic clinic','healthcare solutions','best clinic','one stop clinic'],
})
values = ['all'] + list(df['state'].unique())
dfx = df.loc[((df['state'] == 'oh') & (df['provname'] == '123 healthcare'))]
print(dfx)
# Creating tkinter window and set dimensions
window = tk.Tk()
window.title('Combobox')
window.geometry('500x250')
# label text for title
ttk.Label(window, text = "Main Menu",
background = 'cyan', foreground ="black",
font = ("Times New Roman", 15)).grid(row = 0, column = 1)
#FILTER STATE - PART 1
# Set label
ttk.Label(window, text = "Select the State :",
font = ("Times New Roman", 12)).grid(column = 0,
row = 5, padx = 6, pady = 25)
# Create Combobox
n = tk.StringVar()
state = ttk.Combobox(window, width = 27, textvariable = n)
# Adding combobox drop down list
state['values'] = list(df['state'].unique())
state.grid(column = 1, row = 5)
state.current()
#FILTER FACILITY - PART 2
# Set label
ttk.Label(window, text = "Select the Facility :",
font = ("Times New Roman", 12)).grid(column = 0,
row = 6, padx = 6, pady = 25)
ttk.Button(window, text = "OK", command=on_click).grid(column = 2,
row = 6, padx = 5, pady = 25)
# Create Combobox
n2 = tk.StringVar()
prov = ttk.Combobox(window, width = 27, textvariable = n2)
# Function for when first combobx selected
def state_selected(event):
state_value = state.get()
facilities = list(df.loc[df['state']==state_value]['provname'].unique())
if facilities:
prov['values']=facilities
else:
prov['values']=""
# Bind for when your first combobox is selected
state.bind("<<ComboboxSelected>>", state_selected)
prov.grid(column = 1, row = 6)
prov.current()
window.mainloop()
A few more comments on your code:
prov.current() won't do anything because you haven't selected an index
You don't need from tkinter import Tk because you're already imported tkinter
The problem i'm having is that it even though it executes, the tkinter window remains blank. and as a side issue the window doesn't refresh to update the Actions checkbutton.
from tkinter import *
Pieces = {}
Actions =[]
class GameCreation(Frame):
def __init(self,master):
super(GameCreation,self).__init__(master)
self.grid()
self.CreatePiece()
#Creating pieces function
def CreatePiece(self):
Label(self,text ="What piece are we working with?").grid(row =0,
column = 0,
sticky = W)
self.piece_entry = Entry(self)
self.piece_entry.grid(row =0,
column = 1,
sticky = W)
Label (self, text = "Tick all the actions which the piece has").grid (row =1,
column = 0,
sticky = W)
self.Actions = BooleanVar()
self.Actions.set(None)
column = 0
row = 4
for action in Actions:
Checkbutton(self,text = action, variable = self.checkButton, value = action).grid( row = row,
column = column,
sticky = W)
if column == 5:
row +=1
column = 0
else:
column +=1
Button(self,text = "Add action", command = self.AddAction).grid(row = 1,
column = 0,
sticky = W)
self.action_entry = Entry(self)
self.action_entry.grid(row = 1, column = 1, sticky = W)
Button (self, text = "Create piece and it's actions", command = Add_to_dict).grid(row =2,
column = 0,
sticky = W)
self.Add_dict = Text(self, width =10, height = 2, wrap = WORD)
self.Add_dict.grid( row = 3, column = 0, columnspan = 4)
This function should add to the Actions list
def addAction(self):
action = self.action_entry.get()
Actions.append(action)
This function should just print the name of the piece and the actions chosen for it
def Add_to_dict(self):
actions = Actions.get()
piece = piece_entry.get()
rules = piece, ":", actions
self.Add_dict.delete(0.0,END)
self.Add_dict.insert(0.0,rules)
You need to use __init__, not __init
Also, if you're using BooleanVar, you must set it to True or False, not None:
self.Actions.set(False)
Also, you have a method named addAction but you are calling it like self.AddAction, and you have a method named Add_to_dict that you are calling like Add_to_dict rather than self.Add_to_dict.
And finally, you don't appear to be creating an instance of GameCreation anywhere.
I'm writing a scientific calculator with 2nd button. What is the function for second button so for example it changes sin to sin^-1, plus changing the sin button command; and if you click the 2nd button again, it changes sin^-1 back to sin
I would split my calculator up into section using different frames (one to show the calculations , one with buttons which won't have 2 functions and lastly the buttons which have 2 functions).
The reason I would split it up is because I would use destroying objects and making the new ones this splitting up means you can destroy the wanted frame rather than specific buttons (would require less code). Also for this I would have 3 create GUI defs. one would be the buttons with one function and the bit showing the calculations. one be the buttons which have 2 functions (their first function) and lastly the buttons which have 2 functions (their second functions). To decide between which GUI gen def to use have an if statement with global variable which gets changed each time 2nd function button called and that decides which def to use.
If it was just commands you wanted changing instead of both labels and commands I would have a variable which is etheir 1 or 2(change when 2nd button clicked) then in your definitions (ones which your buttons call) have an if statement to decide between to do normal action (e.g cos) or 2nd action (e.g cos-1).
Here is code below that uses what i have described in the first paragraph:
from tkinter import *
class Calc(Frame):
def __init__(self, master):
self.modefunction = 1
""" Initialize the frame. """
super(Calc,self).__init__(master)
self.grid()
self.calculations_frm = Frame(self, width=100, height=30)#bg = "red"
self.calculations_frm.grid(row = 0, column = 0, columnspan=2)
self.buttons_frm = Frame(self, width= 50, height=30,)#bg = "green")
self.buttons_frm.grid(row = 1, column = 1)
self.buttons_2_functions_1_frm = Frame(self, width=50, height=30)#bg = "blue")
self.buttons_2_functions_1_frm.grid(row = 1, column = 0)
self.create_GUI()
def create_show_calculations(self):
self.calculation_lbl = Label(self.calculations_frm, text = "will show caluclations here").pack()
def create_buttons(self):
#mc stands for mode change
self.mode_change_btn = Button(self.buttons_frm, text = "mc", command = self.mode_change, height = 1, width = 5)
self.mode_change_btn.grid(row = 0,column = 0)
self.plus_btn = Button(self.buttons_frm, text = "plus", height = 1, width = 5)
self.plus_btn.grid(row = 1,column = 0)
def create_GUI(self):
self.create_show_calculations()
self.create_buttons()
self.create_1_function_gui()
def create_1_function_gui(self):
self.tan_btn = Button(self.buttons_2_functions_1_frm, text = "tan", height = 1, width = 5)
self.tan_btn.grid(row = 0,column = 0)
self.san_btn = Button(self.buttons_2_functions_1_frm, text = "san", height = 1, width = 5)
self.san_btn.grid(row = 0,column = 1)
self.coz_btn = Button(self.buttons_2_functions_1_frm, text = "coz", height = 1, width = 5)
self.coz_btn.grid(row = 1,column = 0)
def create_2_function_gui(self):
self.buttons_2_functions_2_frm = Frame(self, width=50, height=30)#bg = "blue")
self.buttons_2_functions_2_frm.grid(row = 1, column = 0)
self.inverse_tan_btn = Button(self.buttons_2_functions_2_frm, text = "tan-1", height = 1, width = 5)
self.inverse_tan_btn.grid(row = 0,column = 0)
self.inverse_san_btn = Button(self.buttons_2_functions_2_frm, text = "san-1", height = 1, width = 5)
self.inverse_san_btn.grid(row = 0,column = 1)
self.inverse_coz_btn = Button(self.buttons_2_functions_2_frm, text = "coz-1", height = 1, width = 5)
self.inverse_coz_btn.grid(row = 1,column = 0)
def mode_change(self):
if self.modefunction == 1:
self.buttons_2_functions_1_frm.destroy()
self.modefunction = 2
self.buttons_2_functions_2_frm = Frame(self, width=50, height=30)#bg = "blue")
self.buttons_2_functions_2_frm.grid(row = 1, column = 0)
self.create_2_function_gui()
else:
self.buttons_2_functions_2_frm.destroy()
self.modefunction = 1
self.buttons_2_functions_1_frm = Frame(self, width=50, height=30)#bg = "blue")
self.buttons_2_functions_1_frm.grid(row = 1, column = 0)
self.create_1_function_gui()
root = Tk()
root.title("booking system")
root.geometry("500x500")
root.configure(bg="white")
app = Calc(root)
root.mainloop()
This is my code:
from tkinter import *
class Car:
def __init__(self, car_id, name, num_seats, available):
self.car_id = car_id
self.name = name
self.num_seats = num_seats
self.available = available
available_cars.append(self.name)
def hire_car(self):
self.available = False
booked_cars.append(self.name)
available_cars.remove(self.name)
def return_car(self):
self.available = True
booked_cars.remove(self.name)
available_cars.append(self.name)
def display():
pass
class Carlist:
def __init__(self, available_cars):
self.available_cars = available_cars
def addCar():
pass
def displayAvailable():
print(available_cars)
def displayBooked():
print(booked_cars)
booked_cars = []
available_cars = []
Car(1,"Suzuki Van", 2, True)
id2 = Car(2,"Toyota Corolla", 4, True)
id3 = Car(3,"Honda Crv", 4, True)
id4 = Car(4,"Suzuki Swift", 4, True)
id5 = Car(5,"Mitsibishi Airtrek", 4, True)
id6 = Car(6,"Nissan DC Ute", 4, True)
id7 = Car(7,"Toyota Previa", 7, True)
Car.hire_car(id3)
Carlist.displayAvailable()
Carlist.displayBooked()
#Interface Code
root = Tk()
root.title("Car Booking System")
frameTop = Frame(root)
frameLeft = Frame(root)
frameRight = Frame(root)
frameBottom = Frame(root)
#Top
topLabel = Label(frameTop, text = "Car Booking System", font = 20).pack()
#Right Side
bookLabel = Label(frameRight, text = "Book:").pack()
varSelectedCar = StringVar()
varSelectedCar.set(available_cars[0])
optionHire = OptionMenu(frameRight, varSelectedCar, *available_cars).pack()
buttonHireCar = Button(frameRight, text = "Enter", command = Car.hire_car).pack()
#Left Side
returnLabel = Label(frameLeft, text = "Return:").pack()
varSelectedCar2 = StringVar()
varSelectedCar2.set(booked_cars[0])
optionReturn = OptionMenu(frameLeft, varSelectedCar2, *booked_cars).pack()
buttonHireCar2 = Button(frameLeft, text = "Enter", command = Car.hire_car).pack()
#Bottom
summaryLabel = Label(frameBottom, text = "Summary:").pack()
#INITIALISATION
frameTop.pack(side = TOP)
frameLeft.pack(side = LEFT)
frameRight.pack(side = RIGHT)
frameBottom.pack(side = BOTTOM)
root.mainloop()
I am trying to link the lists to the GUI interface so when enter is clicked it either runs hire_car or return_car and adds their name to the relevant list. Any idea how to do this? Help would be much appreciated.
The overall idea is to have a program which can book and return cars and as a summary at the bottom....
Although this site is not to make other's homework, you got lucky today. However, please try to figure out how it works. How to update OptionMenu info is from HERE.
from collections import namedtuple
from tkinter import *
Car = namedtuple('Car', 'name num_seats')
class CarList:
ID = 0
def __init__(self):
self.cars, self.hired = {}, set()
def add_car(self, car):
self.cars[self.ID] = car
self.ID += 1
def available_cars(self):
'''Returns the list of (id, Car) tuples sorted by Car.'''
return sorted(((car, id)
for id, car in self.cars.items()
if id not in self.hired))
#staticmethod
def labels(cars_seq):
return ['{} [{}]'.format(t[0].name, t[1])
for t in cars_seq]
def hire_car(self, id):
if id in self.hired:
raise ValueError('That car is already hired.')
self.hired.add(id)
def hired_cars(self):
return sorted(((self.cars[id], id)
for id in self.hired))
def return_car(self, id):
if id not in self.hired:
raise ValueError('That car is not even hired.')
self.hired.remove(id)
def add_car(car):
if not isinstance(car, Car):
raise TypeError('Invalid car object.')
carlist.add_car(car)
update_optionmenus()
def hire_car():
label = opt_hire.var.get()
if label:
id = int(label.rsplit(maxsplit=1)[-1][1:-1])
carlist.hire_car(id)
update_optionmenus()
def return_car():
label = opt_return.var.get()
if label:
id = int(label.rsplit(maxsplit=1)[-1][1:-1])
carlist.return_car(id)
update_optionmenus()
def _update_optionmenu(opt_menu_widget, car_seq):
cars = carlist.labels(car_seq)
if cars:
opt_menu_widget.var.set(cars[0])
else:
opt_menu_widget.var.set('')
opt_menu_widget['menu'].delete(0, END)
for lab in cars:
opt_menu_widget['menu'].add_command(label=lab,
command=lambda lab=lab: opt_menu_widget.var.set(lab))
def update_optionmenus():
_update_optionmenu(opt_hire, carlist.available_cars())
_update_optionmenu(opt_return, carlist.hired_cars())
# You have to initiate a carlist to make it work.
carlist = CarList()
#Interface Code
root = Tk()
root.title('Car Booking System')
frame_top = Frame(root)
frame_top.pack(side = TOP)
frame_left = Frame(root)
frame_left.pack(side = LEFT)
frame_right = Frame(root)
frame_right.pack(side = RIGHT)
frame_bottom = Frame(root)
frame_bottom.pack(side = BOTTOM)
#Top
label_top = Label(frame_top, text = 'Car Booking System',
font = 20).pack()
#Right Side
label_hire = Label(frame_right, text = 'Book:', width=25).pack()
gui_var_hire = StringVar()
opt_hire = OptionMenu(frame_right, gui_var_hire, 'anything')
opt_hire.var = gui_var_hire
del gui_var_hire
opt_hire.pack()
button_hire = Button(frame_right, text = 'Enter',
command = hire_car).pack()
#Left Side
label_return = Label(frame_left, text = 'Return:', width=25).pack()
gui_var_return = StringVar()
opt_return = OptionMenu(frame_left, gui_var_return, 'anything')
opt_return.var = gui_var_return
opt_return.pack()
del gui_var_return
button_return = Button(frame_left, text = 'Enter',
command = return_car).pack()
#Bottom
label_summary = Label(frame_bottom, text = 'Summary:').pack()
add_car(Car('Suzuki Van', 2))
add_car(Car('Toyota Corolla', 4))
add_car(Car('Honda Crv', 4))
add_car(Car('Suzuki Swift', 4))
add_car(Car('Mitsibishi Airtrek', 4))
add_car(Car('Nissan DC Ute', 4))
add_car(Car('Toyota Previa', 7))
add_car(Car('Honda Crv', 2))
root.mainloop()
The following things I want is to add multiple different tasks, and there is a task start button which is used to trig a timer.
class Pomodoro_app(Tk):
def add_task(self):
global time
time = StringVar()
time.set("Start")
task_content = askstring(title = 'Add a Task', prompt = "Input a task")
task_label = Label(self, text = task_content, font = ("Arial, 12")).grid(column = 0, row = 3)
task_start_button = Button(self, textvariable = time, command = self.start_working).grid(column = 1, row = 3)
def createWidgets(self):
self.welcome_label = Label(self, text = "Welcome to the Challenge!", font = ("Arial, 12")).grid(column = 0, row = 0, columnspan = 2)
self.add_task_button = Button(self, text = "Add Task", width = 20, command = self.add_task).grid(column = 0 , columnspan = 2)
def __init__(self):
"""GUI Initiation"""
Tk.__init__(self)
self.createWidgets()
"""window Initiation"""
self.resizable(False, False)
x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
self.geometry('250x400+%d+%d' % (x, y))
Using lambda (or inner function), you can pass additional argument to callback.
For example:
class Pomodoro_app(Tk):
def add_task(self):
global time
time = StringVar()
time.set("Start")
task_content = askstring(title = 'Add a Task', prompt = "Input a task")
task_label = Label(self, text = task_content, font = ("Arial, 12")).grid(column = 0, row = self.next_row)
task_start_button = Button(self, textvariable = time, command = lambda: self.start_working(task_content)).grid(column = 1, row = self.next_row)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
self.next_row += 1
def start_working(self, task_name):
print('start working', task_name)
def createWidgets(self):
self.welcome_label = Label(self, text = "Welcome to the Challenge!", font = ("Arial, 12")).grid(column = 0, row = 0, columnspan = 2)
self.add_task_button = Button(self, text = "Add Task", width = 20, command = self.add_task).grid(column = 0 , columnspan = 2)
def __init__(self):
"""GUI Initiation"""
Tk.__init__(self)
self.createWidgets()
"""window Initiation"""
self.resizable(False, False)
x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
self.geometry('250x400+%d+%d' % (x, y))
self.next_row = 3