I am currently working on a program where I need to change the position of a widget.
Here is my code:
root = Tk()
frame = Frame(root, bg="black")
label1 = Label(frame, text="not important")
label.grid(row=1, column=1)
#some stuff happens
x = aFunctionThatReturnsXCoordinate #not actual name
y = aFunctionThatReturnsYCoordinate
Now I want to change the position of label1 to the new coordinates.
I have tried:
label1.forget_grid()
label1.grid(rows=x, columns=y)
#Ive tried label1/frame.update after this code but it didnt do anything
I've also tried to do it without the grid_forget.
I didn't forget the frame.pack and root.mainloop.
Is there a function to change the position?
I have made a code which contains a label and a button. When the button is pressed , the row of the label changes from 0 to 1 and when pressed again row is changes from 1 to 0 and so on. To make difference between the frame and the root, I have set the color of the frame to sky blue and that of root to pink.
from tkinter import *
global rw;rw = 0
def changed():
global rw;rw += 1;
if rw == 2:rw=0
label.grid(row=rw,column=0)
root = Tk()
root.config(bg="pink")
frame = Frame(root, bg="sky blue")
frame.pack()
label = Label(frame,text="Hello")
label.grid(row=0,column=0)
b = Button(frame, text='Press me!', command=changed)
b.grid(row=0, column=1)
root.mainloop()
Well, the above code is a bit complicated so , if you want a simpler way to do the same:
from tkinter import *
def changed():
size = label.grid_info().get("row") #getting current row
if size == 0:size = 1
elif size == 1:size = 0
label.grid(row=size,column=0)
root = Tk()
root.config(bg="pink")
frame = Frame(root, bg="sky blue")
frame.pack()
label = Label(frame,text="Hello")
label.grid(row=0,column=0)
b = Button(frame, text='Press me!', command=changed)
b.grid(row=0, column=1)
root.mainloop()
Here is an animation:
Here is an example that toggles the position of a label from column 0 to column 1:
You have to keep in mind that unoccupied rows or columns are sized at zero pixels by the grid geometry manager.
pressing the button makes the label in row 1 swap places from column 0 to 1 and vice versa.
import tkinter as tk
def move_label(ndx=[0]):
# the 3 next toggle the column value
rowcol = [(1, 1), (1, 0)]
x, y = rowcol[ndx[0]]
ndx[0] = (ndx[0] + 1) % 2
label_at_1_0.grid(row=x, column=y)
root = tk.Tk()
frame = tk.Frame(root, bg="black")
frame.pack()
label_at_0_0 = tk.Label(frame, text="label_at_0_0")
label_at_0_0.grid(row=0, column=0)
label_at_0_1 = tk.Label(frame, text="not label_at_0_1")
label_at_0_1.grid(row=0, column=1)
label_at_1_0 = tk.Label(frame, text="label_at_1_0")
label_at_1_0.grid(row=1, column=0)
btn_to_move_label = tk.Button(frame, text='move label', command=move_label)
btn_to_move_label.grid(row=1, column=3)
root.mainloop()
Related
I'm making some program, where I input a bunch of stuff into an entry and it gets printed into a row. I also added a feature where you can delete a row. However, when I delete a row, the window does not shrink. The way I actually made the program was by having 2 frames; the main frame with the buttons and entries, and the output or text frame. When I delete a row, it actually appends the data from a list, deletes the frame and all the widgets and reprints the rows, but with out the row I deleted.
The issue with my code, is that when I delete a row, the rows that weren't deleted start to get smaller and compress and secondly, the bottom of the window doesn't move upwards, leaving a blank white space.
Any help would be appreciated, thanks.
actually appending, labelling and printing the row is in function append_entry() and my delete function is delete_row()
from tkinter import *
global main_window
def quit():
main_window.destroy()
def entry_labels():
leader_label = Label(main_frame, text = 'Customer Name')
leader_label.grid(column=0, row=0)
location_label = Label(main_frame, text = 'Receipt Number')
location_label.grid(column=0, row=1)
numcampers_label = Label(main_frame, text = 'Item Hired')
numcampers_label.grid(column=0, row=2)
weather_label = Label(main_frame, text = 'Number Hired')
weather_label.grid(column=0, row=3)
row_label = Label(main_frame, text= 'Row')
row_label.grid(column=3, row=2)
def button():
print_button = Button(main_frame, text = "Print Details", command = append_entry)
print_button.grid(column=3, row=1)
quit_button = Button(main_frame, text= "Quit", command=quit)
quit_button.grid(column=4, row=0)
delete_row_button = Button(main_frame, text = 'Delete Row', command = delete_row)
delete_row_button.grid(column=4, row=3)
def entry():
global name_entry
name_entry = Entry(main_frame)
name_entry.grid(column=1, row=0)
global receipt_entry
receipt_entry = Entry(main_frame)
receipt_entry.grid(column=1, row=1)
global hired_entry
hired_entry = Entry(main_frame)
hired_entry.grid(column=1, row=2)
global num_hired_entry
num_hired_entry = Entry(main_frame)
num_hired_entry.grid(column=1, row=3)
global delete_row_entry
delete_row_entry = Entry(main_frame)
delete_row_entry.grid(column=4, row=2)
def table_headers():
row_header = Label(main_frame, text='Row', font = 'Arial 10 bold')
row_header.grid(column=0, row=4)
customer_header = Label(main_frame, text='Customer Name', font = 'Arial 10 bold')
customer_header.grid(column=1, row=4)
receipt_header = Label(main_frame, text='Receipt Number', font = 'Arial 10 bold')
receipt_header.grid(column=3, row=4)
item_header = Label(main_frame, text='Item Hired', font = 'Arial 10 bold')
item_header.grid(column=2, row=4)
num_header = Label(main_frame, text='Number Hired', font = 'Arial 10 bold')
num_header.grid(column=4, row=4)
def append_entry():
global second_frame
second_frame = Frame(main_window)
second_frame.grid(column=0, row=6)
leader_error_var.set("")
location_error_var.set("")
numcamper_error_var.set("")
weather_error_var.set("")
global name_count
name_count = 0
global ROWS_ABOVE
ROWS_ABOVE = 6
try:
name_entry_str = str(name_entry.get())
hired_entry_str = str(hired_entry.get())
receipt_entry_int = str(receipt_entry.get())
num_hired_entry_int = str(num_hired_entry.get())
if len(name_entry.get()) != 0:
input_data_col1.append([name_entry_str])
input_data_col2.append([hired_entry_str])
input_data_col3.append([receipt_entry_int])
input_data_col4.append([num_hired_entry_int])
counters['total_entries'] += 1
print(input_data_col1)
print(input_data_col2)
print(input_data_col3)
print(input_data_col4)
while name_count < counters ['total_entries']:
global name
name = Label(second_frame, text=(input_data_col1[name_count][-1])) ##using -1 selects the latest entry in the list
name.grid(column=1, row=name_count + ROWS_ABOVE, padx=50)
item = Label(second_frame, text=(input_data_col2[name_count][-1]))
item.grid(column=2, row=name_count + ROWS_ABOVE, padx=50)
row = Label(second_frame, text=name_count)
row.grid(column=0, row=name_count + ROWS_ABOVE, padx=60)
receipt = Label(second_frame, text=(input_data_col3[name_count][-1]))
receipt.grid(column=3, row=name_count + ROWS_ABOVE, padx=50)
num = Label(second_frame, text=(input_data_col4[name_count][-1]))
num.grid(column=4, row= name_count + ROWS_ABOVE, padx=50)
name_count += 1
name_entry.delete(0,END)
receipt_entry.delete(0,END)
hired_entry.delete(0,END)
num_hired_entry.delete(0,END)
except:
leader_error_var.set("Check inputs")
#location_error_var.set("please enter a valid num")
#numcamper_error_var.set("numcamper error test")
weather_error_var.set("")
name_entry.delete(0,END)
receipt_entry.delete(0,END)
hired_entry.delete(0,END)
num_hired_entry.delete(0,END)
def delete_row():
user_del =int(delete_row_entry.get())
counters['total_entries'] -= 1
input_data_col1.pop(user_del)
input_data_col2.pop(user_del)
input_data_col3.pop(user_del)
input_data_col4.pop(user_del)
data = [input_data_col1,input_data_col2,input_data_col3,input_data_col4]
for widget in second_frame.winfo_children():
widget.destroy()
append_entry()
print(input_data_col1)
print(input_data_col2)
print(input_data_col3)
print(input_data_col4)
def error_prevention():
#leader_error_var.set("leader error test")
#location_error_var.set("location error test")
#numcamper_error_var.set("numcamper error test")
#weather_error_var.set("weather error test")
#weather_error_var.set("_______________")
leader_error = Label(main_frame, textvariable = leader_error_var, fg = 'red')
leader_error.grid(column=2, row=0)
location_error = Label(main_frame, textvariable = location_error_var, fg = 'red')
location_error.grid(column=2, row=1)
numcamper_error = Label(main_frame, textvariable = numcamper_error_var, fg = 'red', width = 13)
numcamper_error.grid(column=2, row=2)
weather_error = Label(main_frame, textvariable = weather_error_var, fg = 'red')
weather_error.grid(column=2, row=3)
def main():
global main_window
main_window = Tk()
global input_data_col1
input_data_col1 = []
global input_data_col2
input_data_col2 = []
global input_data_col3
input_data_col3 = []
global input_data_col4
input_data_col4 = []
global input_data
input_data = []
global main_frame
main_frame = Frame(main_window)
main_frame.grid(row=0,column=0)
global counters
counters = {'total_entries':0, 'name_count':0}
#global number
#number = {'total_entries':0}
def stringvars():
global location_error_var
location_error_var = StringVar()
location_error_var.set("")
global numcamper_error_var
numcamper_error_var = StringVar()
numcamper_error_var.set("")
global leader_error_var
leader_error_var = StringVar()
leader_error_var.set("")
global weather_error_var
weather_error_var = StringVar()
leader_error_var.set("")
stringvars()
entry_labels()
entry()
error_prevention()
button()
table_headers()
main()
main_window.mainloop()
Under the code
for widget in second_frame.winfo_children():
widget.destroy()
add this block of code
second_frame.pack()
it will be like this
for widget in second_frame.winfo_children():
widget.destroy()
second_frame.pack()
I hope this helps you
You can use
main_window.geometry("1200x800+100+100")
to change size and position of main_window. Here the window width will be 1200 and height will be 800, positioned 100px to the top left corner of screen. The +100+100 is optional.
You may add geometry() to delete_row callback to resize the frame. Though you might have to calculate the proper size after widget deletion.
As to "when I delete a row, the rows that weren't deleted start to get smaller and compress",
That's due to how grid layout works. If there are two widgets on the same grid row, the grid height will be equal the the higher widget height. When the higher widget is removed, the grid will resize to the smaller widget height and appear to 'shrink'.
To solve that, you can try add padding to the widget, the syntax is
widget.grid(column=1,row=1,padx=(10,10),pady=(10,10))
Alternatively, you may try other layout management: .place will give you absolute layout control. Or you can use pack and let tkinter decide the proper position.
I'm creating a program with Tkinter, It have 6 entry labels.
I'm with difficulty to grid these labels in the center of page.
I don't wanna to use .pack
How can I set the number of columns that the grid has? It seems tkinter ignore when I set column=6 for example.
here my code:
##Input 1 / Input de parametros
self.PwNomeLabel1 = Label(text = "Cliente:")
self.PwNomeLabel1["font"] = ("10")
self.PwNomeLabel1.grid(row=0,column=2,sticky=W)
self.inputpwtest1 = Entry(borderwidth= 2, validate='key')
self.inputpwtest1["width"] = 30
self.inputpwtest1.grid(row=0, column=3)
##Input 2
self.PwNomeLabel2 = Label(text = "Responsavel por Teste:")
self.PwNomeLabel2["font"] = ("10")
self.PwNomeLabel2.grid(row=1,column=2,sticky=W)
self.inputpwtest2 = Entry(borderwidth= 2, validate='key')
self.inputpwtest2["width"] = 30
self.inputpwtest2.grid(row=1, column=3)
##Input 3
self.PwNomeLabel3 = Label(text = "Nome do Sistema:")
self.PwNomeLabel3["font"] = ("10")
self.PwNomeLabel3.grid(row=2,column=2,sticky=W)
self.inputpwtest3 = Entry(borderwidth= 2, validate='key')
self.inputpwtest3["width"] = 30
self.inputpwtest3.grid(row=2,column=3)
##Input 4
self.PwNomeLabel4 = Label(text = "Ref:")
self.PwNomeLabel4["font"] = ("10")
self.PwNomeLabel4.grid(row=3,column=2,sticky=W)
self.inputpwtest4 = Entry(borderwidth= 2, validate='key')
self.inputpwtest4["width"] = 30
self.inputpwtest4.grid(row=3,column=3)
##Input 5
self.PwNomeLabel5 = Label(text = "Data Base:")
self.PwNomeLabel5["font"] = ("10")
self.PwNomeLabel5.grid(row=4,column=2,sticky=W)
self.inputpwtest5 = Entry(borderwidth= 2, validate='key')
self.inputpwtest5["width"] = 30
self.inputpwtest5.grid(row=4,column=3)
##Input 6
self.PwNomeLabel6 = Label(text = "Data Teste:")
self.PwNomeLabel6["font"] = ("10")
self.PwNomeLabel6.grid(row=5,column=2,sticky=W)
self.inputpwtest6 = Entry(borderwidth= 2, validate='key')
self.inputpwtest6["width"] = 30
self.inputpwtest6.grid(row=5,column=3)
root = Tk()
root.title("TEST PLATFORM")
Application(root)
root.geometry('1366x768')
root.mainloop()
In this way its results:
If I change label columns to "4" and "5" for the entry results:
Like the prints, It seems the Tkinter get confused and the grid stay desorganized
As mentioned in the comments you are likely needing to manage row/column weights.
Here is an example that does that while also showing how you can reduce your code by dynamically generating labels and entry fields instead of writing a wall of text for all of them.
import tkinter as tk
root = tk.Tk()
root.geometry('800x500')
root.title("TEST PLATFORM")
label_list = ['Cliente:', 'Responsavel por Teste:', 'Nome do Sistema:', 'Ref:', 'Data Base:', 'Data Teste:']
entry_list = []
# Row and Column configure to manage weights
root.columnconfigure(0, weight=1)
root.columnconfigure(2, weight=1)
root.rowconfigure(0, weight=1)
root.rowconfigure(2, weight=1)
# Add a frame to hold the rest of the widgets and place that frame in the row/column without a weight.
# This will allow us to center everything that we place in the frame.
frame = tk.Frame(root)
frame.grid(row=1, column=1)
# use a loop to create our widgets.
for ndex, label in enumerate(label_list):
tk.Label(frame, text=label, font='10').grid(row=ndex, column=0, sticky='w')
# Store the entry widgets in a list for later use
entry_list.append(tk.Entry(frame, borderwidth=2, width=30))
entry_list[-1].grid(row=ndex, column=1)
# Get and print each entry value.
def print_entries():
for entry in entry_list:
print(entry.get())
tk.Button(frame, text='Selecionar Arquivo', command=print_entries).grid(row=len(label_list)+1, column=0, columnspan=2)
root.mainloop()
If a column is empty (no widget inside), then it will not appear.
In the following example, I put a frame in column 0 with width=100 in order to have my column 1 "centered". I also have the parameter weight=1 for the 3 columns, so it grows the same way when I expand the window.
import tkinter as tk
root = tk.Tk()
for i in range(3):
root.columnconfigure(i, weight=1)
tk.Frame(root, width=100).grid(row=0, column=0, sticky='w')
# tk.Label(root, text='Left').grid(row=0, column=0, sticky='w')
tk.Label(root, text='Center').grid(row=0, column=1)
tk.Label(root, text='Right').grid(row=0, column=2, sticky='e')
root.mainloop()
I'm a car park admittance thingy for college. Basically what is does when it's run, a window comes up, asks the user to enter make, model, colour, and reg plate. Then it saves this data to a list, array or whatever. The user presses a button to enter their car into the car park, and also to see what cars are currently in the car park. When I press admit vehicle, I need the data to be saved to this list/array/tree, and also for a integer variable to decrease by one. Here's the relevant code. There is more, but this is the relevant bits.
# Admit Button
btn_admit = ttk.Button(bottom_frame)
btn_admit.config(text='Admit Vehicle')
btn_admit.bind('<Button-1>', self.admit) # I need this to reduce the variable as well
...
def admit(self, event):
self.useful_msg.set("Vehicle Admitted") # This is only here to show a message currently it does nothing else
This is the 'spaces available' variable:
self.num_spaces = IntVar(mid_frame)
self.num_spaces.set = 0
lbl_num_spaces = Label(mid_frame)
lbl_num_spaces.config(textvariable=self.num_spaces, bg='yellow')
Finally, this is the code for the window that shows the tree of cars that are in the car park (with some example cars hard-coded for now):
class ShowCarsGui:
def __init__(self, master):
self.master = master
self.master.geometry('1200x600+100+100')
# Frames
top_frame = tk.Frame(self.master)
tree_container = tk.Frame(self.master)
bottom_bar = tk.Frame(self.master)
# Widgets:
# Logo
carpark_icon = tk.PhotoImage(file='car.gif')
lbl_carpark_icon = tk.Label(top_frame)
lbl_carpark_icon.config(image=carpark_icon)
lbl_carpark_icon.image = carpark_icon
# Header
lbl_header = tk.Label(top_frame)
lbl_header.config(text="Vehicles in car park", font='helvetica 32 bold')
# Tree(ttk)
self.tree = ttk.Treeview(tree_container)
self.tree["columns"] = ("Make", "Model", "Colour", "Registration")
self.tree["height"] = 10
self.tree["show"] = 'headings' # Gets rid of default first column
vsb = ttk.Scrollbar(tree_container)
vsb.configure(orient='vertical', command=self.tree.yview)
hsb = ttk.Scrollbar(tree_container)
hsb.configure(orient='horizontal', command=self.tree.xview)
self.tree.configure(yscroll=vsb.set, xscroll=hsb.set)
self.tree_populate()
# Button
quit_button = tk.Button(bottom_bar)
quit_button.config(text='Quit', width=25)
quit_button.bind('<Button-1>', self.close_window)
# Positioning frames
top_frame.grid_rowconfigure(0, minsize=150) # Make row 150 pixels high
top_frame.grid(row=0)
tree_container.grid(row=1)
bottom_bar.grid(row=2)
# Top
lbl_carpark_icon.grid(row=0, column=0, padx=10, sticky='w')
lbl_header.grid(row=0, column=1, padx=20)
# Middle
self.tree.grid(column=0, row=0, sticky='nsew')
vsb.grid(column=1, row=0, sticky='ns')
hsb.grid(column=0, row=1, sticky='ew')
# Bottom
quit_button.grid(row=0, column=0)
def close_window(self, event):
self.master.destroy()
def tree_populate(self):
# Eventually this needs to come from car park object
tree_columns = ("Make", "Model", "Colour", "Registration")
tree_data = [
("Ford", "Ka", "Blue", "FD54 2WE"),
("Vauxhall", "Corsa", "Green", "KJ61 9YH"),
("VW", "Polo", "Silver", "AA54 9TQ"),
("Nissan", "Qashqai", "Red", "YRE 456W"),
("Toyota", "Starlet", "Gold", "J234 WYE"),
]
for col in tree_columns:
self.tree.heading(col, text=col, anchor='w')
for country_data in tree_data:
self.tree.insert("", 0, values=country_data)
Finally here is the code for the entire program:
import tkinter as tk
from tkinter import *
from tkinter import ttk
class CarParkGui:
def __init__(self, master):
self.master = master
self.master.configure(bg='light cyan')
self.master.title("Collyer's Car Park")
self.master.option_add('*Font', 'Georgia 12') # Font for all widgets
self.master.option_add('*Font', 'helvetica 20 bold')
self.master.option_add('*Background', 'light cyan') # background of all widgets
self.master.geometry('1200x500+100+100') # w,h,x,y (top left corner)
self.top() # Build top bar
self.middle() # Define middle frame
self.bottom() # Define Bottom Frame
def top(self):
# Frame for top section
top_frame = Frame(self.master)
# Logo
carpark_icon = PhotoImage(file='car.gif')
lbl_carpark_icon = Label(top_frame) # Instance of tkinter label (parent is frame)
lbl_carpark_icon.config(image=carpark_icon)
lbl_carpark_icon.image = carpark_icon # Have to have this as well as previous one
# Header
lbl_header = Label(top_frame)
lbl_header.config(text='Admit Vehicle', font='helvetica 32 bold')
# Grid positioning for top frame
top_frame.grid_rowconfigure(0, minsize=150) # Make row 150 pixels high
top_frame.grid(row=0)
# Within Frame
lbl_carpark_icon.grid(row=0, column=0, padx=10)
lbl_header.grid(row=0, column=1, padx=20)
def middle(self):
# Frame to contain other widgets
mid_frame = Frame(self.master)
# Label - Car Make
lbl_make = Label(mid_frame)
lbl_make.config(text='Make') # Presentation
# Label - Car Model
lbl_model = Label(mid_frame)
lbl_model.config(text='Model')
# Label - Colour
lbl_colour = Label(mid_frame)
lbl_colour.config(text='Colour')
# Label - Registration
lbl_reg = Label(mid_frame)
lbl_reg.config(text='Registration')
# Label - Spaces
lbl_spc = Label(mid_frame)
lbl_spc.config(text='Spaces')
# Text Entry - Make
self.make = StringVar(mid_frame)
txt_make = Entry(mid_frame)
txt_make.config(textvariable=self.make, width=20)
# Text Entry - Model
self.model = StringVar(mid_frame)
txt_model = Entry(mid_frame)
txt_model.config(textvariable=self.model, width=20)
# Text Entry - Colour
self.colour = StringVar(mid_frame)
txt_colour = Entry(mid_frame)
txt_colour.config(textvariable=self.colour, width=20)
# Text Entry - Registration
self.reg = StringVar(mid_frame)
txt_reg = Entry(mid_frame)
txt_reg.config(textvariable=self.reg, width=20)
# Label for number of space available (WILL BE UPDATED)
self.num_spaces = IntVar(mid_frame)
self.num_spaces.set = 0
lbl_num_spaces = Label(mid_frame)
lbl_num_spaces.config(textvariable=self.num_spaces, bg='yellow')
# Display
mid_frame.grid_columnconfigure(0, minsize=100) # Make row 150 pixels high
mid_frame.grid(row=1, sticky='w')
# Row 0
lbl_make.grid(row=1, column=0)
txt_make.grid(row=1, column=1)
lbl_spc.grid(row=1, column=2)
lbl_num_spaces.grid(row=1, column=3, sticky='w')
# Row 1
lbl_model.grid(row=2, column=0)
txt_model.grid(row=2, column=1, padx='10')
# Row 2
lbl_colour.grid(row=3, column=0)
txt_colour.grid(row=3, column=1, padx='10')
# Row 3
lbl_reg.grid(row=4, column=0)
txt_reg.grid(row=4, column=1, padx='10')
def bottom(self):
# Frame for bottom section
bottom_frame = Frame(self.master)
# Grid reference for bottom frame
bottom_frame.grid(row=2)
# Guidance message (WILL BE UPDATED)
self.useful_msg = StringVar(bottom_frame)
self.useful_msg.set("Enter your vehicle details")
self.lbl_msg = Label(bottom_frame) # Use self so we can change config at
self.lbl_msg.config(textvariable=self.useful_msg, fg='red', width=20)
# Admit Button
btn_admit = ttk.Button(bottom_frame)
btn_admit.config(text='Admit Vehicle')
btn_admit.bind('<Button-1>', self.admit)
# Show Vehicles Button
btn_show = ttk.Button(bottom_frame)
btn_show.config(text='Show Vehicles In Car Park')
btn_show.bind('<Button-1>', self.show)
# Within bottom_frame
# row 0
self.lbl_msg.grid(row=0, column=0)
# row 1
btn_admit.grid(row=1, column=0, sticky='e')
btn_show.grid(row=1, column=1, sticky='e')
def admit(self, event):
self.useful_msg.set("Vehicle Admitted")
def show(self, event):
self.new_window = Toplevel(self.master)
self.app = ShowCarsGui(self.new_window)
___ This is where ShowCarsGui() is ____
def main():
root = Tk()
CarParkGui(root)
root.mainloop()
main()
To do "two things with one button", the correct solution is to create a function that does these "two things", and then associate that function with the button.
btn_admit = ttk.Button(bottom_frame)
btn.configure(command=self.admit)
def admit(self):
self.num_spaces.set(self.num_spaces.get()-1)
self.useful_msg.set("Vehicle Admitted")
Note: the above example uses the command attribute rather than a binding. Using the command attribute is preferable because it has built-in support for keyboard traversal. And, of course, you can do as much or as little as you want in admit -- you aren't limited to one or two things.
This should be a very very simple problem. I'm making a GUI in which I have multiple entry widgets... about 30 or so all in one column. Instead of making each box one by one it seems like a better idea to just generate the widgets with a loop. However, I'm finding it extremely difficult to .get() values from the entry widgets, and convert them into floats. This is what I have so far... any help would be greatly appreciated.
class Application(Frame):
def __init__(root,master):
Frame.__init__(root,master)
root.grid()
root.create_widgets()
def calcCR(root):
d1 = root.enter.get()
d1 = float(d1)
#root.answer.delete(0.0,END)
a = 'The C/R Alpha is! %lf \n' % (d1)
root.answer.insert(0.0, a)
def create_widgets(root):
### Generate Element List ###
for i in range(len(elem)):
Label(root, text=elem[i]).grid(row=i+1, column=0)
### Generate entry boxes for element wt% ###
for i in range(len(elem)):
enter = Entry(root, width = 8)
enter.grid(row = i+1,column=1)
enter.insert(0,'0.00')
root.button = Button(root, text = 'Calculate C/R', command = root.calcCR)
root.button.grid(row=11, column=2, sticky = W, padx = 10)
root.answer = Text(root, width = 50, height = 12.5, wrap = WORD)
root.answer.grid(row=1, column=2, rowspan = 10, sticky = W, padx = 10)
root = Tk()
root.title('C/R Calculator')
app = Application(root)
root.mainloop()
Put the Entry instances into a list.
from tkinter import Tk, Frame, Label, Entry, Button
class App(Frame):
def __init__(root, master):
Frame.__init__(root, master)
root.grid()
root.create_widgets()
def get_values(root):
return [float(entry.get()) for entry in root.entries]
def calc_CR(root):
answer = sum(root.get_values()) #Replace with your own calculations
root.answer.config(text=str(answer))
def create_widgets(root):
root.entries = []
for i in range(20):
label = Label(root, text=str(i))
label.grid(row=i, column=0)
entry = Entry(root, width=8)
entry.grid(row=i, column=1)
entry.insert(0, '0.00')
root.entries.append(entry)
root.calc_button = Button(root, text='Calculate C/R', command=root.calc_CR)
root.calc_button.grid(row=20, column=0)
root.answer = Label(root, text='0')
root.answer.grid(row=20, column=1)
def run(root):
root.mainloop()
root = Tk()
root.title('C/R Calculator')
app = App(root)
app.run()
HI i am trying to place the alignment of my Entry(Text Box) according to the image below. I tried everything, TOP BOTTOM LEFT RIGHT.
This is the alignment i want. Obtained from paint program*
Problem
Coding of tkinter
master = Tk.Tk() # Open up GUI connection
master.title('Program Application')
print "VSM activated input range first (X2 must be larger than X1)"
#Declare button and respective method
button = Tk.Button(text='VSM', command=VSM, fg="red")
button.config( height = 10, width = 80 )
button.pack() #pack is needed to display the button
bluebutton = Tk.Button(text="AGM Folder",command= lambda: Folder(0), fg="blue").pack(side = LEFT)
bluebutton = Tk.Button(text="VSM Folder",command= lambda: Folder(1), fg="blue").pack(side = RIGHT)
Label(text='Correct Range for Gradient\nX2 X1').pack(side=TOP,padx=10,pady=10)
entryX2 = Entry(master, width=10)
entryX2.pack(side=LEFT,padx=10,pady=10)
entryX1 = Entry(master,width=10)
entryX1.pack(side=RIGHT,padx=10,pady=10)
buttonGradient = Tk.Button(text='Input Range OP',command= lambda: Folder(2), fg="red").pack()
entryX2IP = Entry(master, width=10)
entryX2IP.pack(side=LEFT,padx=10,pady=10)
entryX1IP = Entry(master,width=10)
entryX1IP.pack(side=RIGHT,padx=10,pady=10)
btnGradientIP = Tk.Button(text='Input Range IP',command= lambda: Folder(2), fg="red").pack(side = TOP)
master.mainloop() # Continue loop till user close tab
Use Frame:
master = Tk.Tk() # Open up GUI connection
master.title('Program Application')
print "VSM activated input range first (X2 must be larger than X1)"
#Declare button and respective method
button = Tk.Button(text='VSM', command=VSM, fg="red")
button.config( height = 10, width = 80 )
button.pack() #pack is needed to display the button
bluebutton = Tk.Button(text="AGM Folder",command= lambda: Folder(0), fg="blue").pack(side = LEFT)
bluebutton = Tk.Button(text="VSM Folder",command= lambda: Folder(1), fg="blue").pack(side = RIGHT)
Label(text='Correct Range for Gradient\nX2 X1').pack(side=TOP,padx=10,pady=10)
################### Use 3 frames to contains entries, buttons.
frameX2 = Frame(master)
frameX2.pack(side=LEFT, expand=1, anchor=E)
entryX2 = Entry(frameX2, width=10)
entryX2.pack(side=TOP,padx=10,pady=10)
entryX2IP = Entry(frameX2, width=10)
entryX2IP.pack(side=TOP,padx=10,pady=10)
frameButton = Frame(master)
frameButton.pack(side=LEFT)
Tk.Button(frameButton, text='Input Range OP',command= lambda: Folder(2), fg="red").pack(padx=10, pady=10)
Tk.Button(frameButton, text='Input Range IP',command= lambda: Folder(2), fg="red").pack(padx=10, pady=10)
frameX1 = Frame(master)
frameX1.pack(side=LEFT, expand=1, anchor=W)
entryX1 = Entry(frameX1,width=10)
entryX1.pack(side=TOP,padx=10,pady=10)
entryX1IP = Entry(frameX1,width=10)
entryX1IP.pack(side=TOP,padx=10,pady=10)
#####################
master.mainloop() # Continue loop till user close tab