I'm sure it's a quick fix, but I just can't seem to figure out how to align my entry text boxes (in column 4) with the images & buttons in (columns 1-3). Here is my code, and an image of actual verse desired output:
I've tried changing the column and row position of t1 - t3 (CHAPTER NUMBER INPUTS) but they still appear shifted below the other grid "boxes" instead of in the same row.
from tkinter import *
from tkinter import ttk
# pip install pillow
# from pillow import Image, ImageTk
from PIL import ImageTk, Image
WD = Tk() # window
FM = Frame(WD) # frame
FM.grid(row=0,column=0)
# LABELS
lblA = Label(FM, text="Image 1", font=("Arial Bold", 20))
lblB = Label(FM, text="Image 2", font=("Arial Bold", 20))
lblC = Label(FM, text="Image 3", font=("Arial Bold", 20))
# LABEL POSITIONS
lblA.grid(row=0, column=1)
lblB.grid(row=1, column=1)
lblC.grid(row=2, column=1)
# CHAPTER NUMBER INPUTS
#ch1 = ""
t1 = Text()
t2 = Text()
t3 = Text()
# t1.config(wrap=WORD)
# t2.config(wrap=WORD)
# t3.config(wrap=WORD)
#ch1_entry = Entry(FM, width=8, textvariable=ch1)
t1.grid(row=0, column=4)#, sticky=(S, W))
t2.grid(row=1, column=4)#, sticky=(S, W))
t3.grid(row=2, column=4)#, sticky=(S, W))
# BUTTONS
btnA1 = Button(FM, text ="Move Up")
btnA2 = Button(FM, text ="Move Down")
btnB1 = Button(FM, text ="Move Up")
btnB2 = Button(FM, text ="Move Down")
btnC1 = Button(FM, text ="Move Up")
btnC2 = Button(FM, text ="Move Down")
# BUTTON POSITIONS
btnA1.grid(row=0,column=2, sticky="n")
btnA2.grid(row=0,column=2, sticky="s")
btnB1.grid(row=1,column=2, sticky="n")
btnB2.grid(row=1,column=2, sticky="s")
btnC1.grid(row=2,column=2, sticky="n")
btnC2.grid(row=2,column=2, sticky="s")
# IMAGES
load1 = Image.open("parrot.jpg")
renderA = ImageTk.PhotoImage(load1)
renderB = ImageTk.PhotoImage(load1)
renderC = ImageTk.PhotoImage(load1)
imgA = Label(FM, image=renderA)
imgB = Label(FM, image=renderB)
imgC = Label(FM, image=renderC)
imgA.image = renderA
imgB.image = renderB
imgC.image = renderC
# IMAGE POSITIONS
imgA.grid(row=0, column=3)
imgB.grid(row=1, column=3)
imgC.grid(row=2, column=3)
#root = Tk()
#app = Window(root)
#root.wm_title("Tkinter window")
#root.geometry("400x120")
WD.mainloop()
The images, buttons, and label are children of FM but the text widgets are children of root. If you want the text widgets aligned with everything else then they also need to be children of FM
t1 = Text(FM)
t2 = Text(FM)
t3 = Text(FM)
If you want the image to control the height of a row, you can give the text widget a height of 1 and then use the sticky attribute to cause it to expand to fill the height created by the image.
t1 = Text(FM, height=1)
t2 = Text(FM, height=1)
t3 = Text(FM, height=1)
...
t1.grid(row=0, column=4, sticky="nsew")
t2.grid(row=1, column=4, sticky="nsew")
t3.grid(row=2, column=4, sticky="nsew")
Related
I am new to tkinter and learning to organize the frames in tkinter.
In the following code, I have created 3 label frames.
The frames are not aligned as per my requirements and I would like to get help organizing them cleanly.
Required
===========
By default it gives me following layout
LabelFrame1 LabelFrame2
LabelFrame3
I would like to have left aligned label frames like this:
LabelFrame1 LabelFrame2
LabelFrame3
How to align all label frames to left so that I can have spaces in right?
MWE
# %%writefile a.py
import tkinter as tk
from tkinter import ttk,messagebox
# variables
padding = dict(padx=20,pady=20)
padding_widget = dict(padx=10,pady=5)
# root app
win = tk.Tk()
w,h = 800, 600 # app
ws, hs = win.winfo_screenwidth(), win.winfo_screenheight() # screen
x,y = -10,hs*0.1
win.geometry('%dx%d+%d+%d' % (w, h, x, y))
#===================== end of Snippets =====================================
# Frame contains labelframes
f = tk.Frame(win,height=200, width=200)
f.grid(row=0,column=0,padx=20, pady=20)
f.pack(fill="both", expand="yes")
#=============================================================================
# label frame: Find and Replace
lf00 = tk.LabelFrame(f,text='Find and Replace from Clipboard')
lf00.grid(row=0,column=0,padx=20, pady=20)
b = tk.Button(lf00,text='Click to Replace')
b.grid(row=2,column=0,sticky='news',**padding)
#=============================================================================
# label frame: Text Manipulation
lf01 = tk.LabelFrame(f,text='Text Manipulation')
lf01.grid(row=0,column=1,padx=20, pady=20)
b = tk.Button(lf01,text='Click to Replace')
b.grid(row=2,column=0,sticky='news',**padding)
#=============================================================================
# LabelFrame: Calculator
lf10 = tk.LabelFrame(f,text='Calculator')
lf10.grid(row=1,column=0,padx=10, pady=10)
l_exp = tk.Label(lf10,text="Expression")
t_i = tk.Text(lf10, height=2, width=70, bg="light yellow", padx=0,pady=0)
t_o = tk.Text(lf10, height=4, width=40, bg="light cyan",padx=0,pady=0)
b_calc = tk.Button(lf10,height=1,width=10,text="Calculate")
l_exp.pack();t_i.pack();b_calc.pack();t_o.pack()
# Main window
win.config()
win.mainloop()
Update
# %%writefile a.py
import tkinter as tk
from tkinter import ttk,messagebox
# variables
padding = dict(padx=20,pady=20)
padding_widget = dict(padx=10,pady=5)
# root app
win = tk.Tk()
w,h = 800, 600 # app
ws, hs = win.winfo_screenwidth(), win.winfo_screenheight() # screen
x,y = -10,hs*0.1
win.geometry('%dx%d+%d+%d' % (w, h, x, y))
#===================== end of Snippets =====================================
# Frame contains labelframes
f = tk.Frame(win,height=200, width=200)
f.grid(row=0,column=0,padx=20, pady=20,sticky="w")
f.pack(fill="both", expand="yes")
#=============================================================================
# label frame: Find and Replace
lf00 = tk.LabelFrame(f,text='Find and Replace from Clipboard')
lf00.grid(row=0,column=0,padx=20, pady=20,sticky="w")
b = tk.Button(lf00,text='Click to Replace')
b.grid(row=2,column=0,sticky='w',**padding)
#=============================================================================
# label frame: Text Manipulation
lf01 = tk.LabelFrame(f,text='Text Manipulation')
lf01.grid(row=0,column=1,padx=20, pady=20,sticky="w")
b = tk.Button(lf01,text='Click to Replace')
b.grid(row=2,column=0,sticky='w',**padding)
#=============================================================================
# LabelFrame: Calculator
lf10 = tk.LabelFrame(f,text='Calculator')
lf10.grid(row=1,column=0,padx=10, pady=10,sticky="w")
l_exp = tk.Label(lf10,text="Expression")
t_i = tk.Text(lf10, height=2, width=70, bg="light yellow", padx=0,pady=0)
t_o = tk.Text(lf10, height=4, width=40, bg="light cyan",padx=0,pady=0)
b_calc = tk.Button(lf10,height=1,width=10,text="Calculate")
l_exp.pack();t_i.pack();b_calc.pack();t_o.pack()
# Main window
win.config()
win.mainloop()
For greater clarity, first draw on a piece of paper what you want to place in the window. Like this:
And you will see that you need to stretch tk.LabelFrame(f, text='Calculator') over several cells ( columnspan=3).
import tkinter as tk
from tkinter import ttk, messagebox
# variables
padding = dict(padx=20, pady=20)
padding_widget = dict(padx=10, pady=5)
# root app
win = tk.Tk()
w, h = 800, 600 # app
ws, hs = win.winfo_screenwidth(), win.winfo_screenheight() # screen
x, y = -10, hs * 0.1
win.geometry('%dx%d+%d+%d' % (w, h, x, y))
# ===================== end of Snippets =====================================
# Frame contains labelframes
f = tk.Frame(win, height=200, width=200)
f.grid(row=0, column=0, padx=20, pady=20)
f.pack(fill="both", expand="yes")
f.columnconfigure(1, weight=1)
# =============================================================================
# label frame: Find and Replace
lf00 = tk.LabelFrame(f, text='Find and Replace from Clipboard')
lf00.grid(row=0, column=0, padx=(20, 2), pady=20, sticky='e')
b = tk.Button(lf00, text='Click to Replace')
b.grid(row=0, column=0, sticky='nswe', **padding)
# =============================================================================
# label frame: Text Manipulation
lf01 = tk.LabelFrame(f, text='Text Manipulation')
lf01.grid(row=0, column=1, padx=2, pady=20, sticky='w')
b = tk.Button(lf01, text='Click to Replace')
b.grid(row=0, column=0, sticky='nswe', **padding)
# =============================================================================
# LabelFrame: Calculator
lf10 = tk.LabelFrame(f, text='Calculator')
lf10.grid(row=1, column=0, columnspan=3, padx=20, pady=20, sticky='w')
l_exp = tk.Label(lf10, text="Expression")
t_i = tk.Text(lf10, height=2, width=70, bg="light yellow", padx=0, pady=0)
t_o = tk.Text(lf10, height=4, width=40, bg="light cyan", padx=0, pady=0)
b_calc = tk.Button(lf10, height=1, width=10, text="Calculate")
l_exp.pack()
t_i.pack()
b_calc.pack()
t_o.pack()
# Main window
win.config()
win.mainloop()
I've made a simple GUI for placing objects in RoboDK via a Python script using Tkinter.
Essentailly, the user selects an object using the btnSelect button, which then updates the entry widgets with its coordinates (x, y, z, then Euler rotation). The user can then edit the entry widgets then select the "Move object" button (or btnMove in the code) to move the object to the new position. However, when selecting an object for the second time, the entry fields cannot be edited without selecting a new object.
from tkinter.constants import DISABLED, NORMAL, CENTER, END
from typing import *
import tkinter as tk
import threading
from robolink import * # RoboDK API
from robodk import * # Robot toolbox
X_MAX = 500
X_MIN = 0
Y_MAX = 300
Y_MIN = -360
ROTZ_MAX = 180
ROTZ_MIN = -180
# Keep track of selected item
obj = None
def main():
rdk = Robolink()
window = buildGUI(rdk)
window.mainloop()
def buildGUI(rdk: Robolink) -> tk.Tk:
window = tk.Tk()
canvas = tk.Canvas(window, width=200)
canvas.grid(columnspan=3, rowspan=14)
# Set the window title (must be unique for the docking to work, try to be creative)
window_title = 'Move object window'
window.title(window_title)
title = tk.Label(window, text="Move Object", font="none 14 bold")
title.grid(columnspan=3, column=0, row=0)
# Delete the window when we close it
window.protocol("WM_DELETE_WINDOW", lambda: onClose(window))
deadspace1 = tk.Label(text="")
deadspace1.grid(columnspan=3, column=0, row=1)
selectText = tk.StringVar()
btnSelect = tk.Button(window, textvariable=selectText, height=2, width=0,
bg="#bbbbbb", fg='white', justify=CENTER)
selectText.set("Select object")
btnSelect.grid(column=1, row=2)
deadspace2 = tk.Label("")
deadspace2.grid(columnspan=3, column=0, row=3)
objName = tk.StringVar()
objLabel = tk.Label(window, textvariable=objName, font="none 12 bold")
objName.set("None Selected")
objLabel.grid(columnspan=3, column=0, row=4)
deadspace2 = tk.Label("")
deadspace2.grid(columnspan=3, column=0, row=5)
# Position options
xLabel = tk.Label(window, text="x: ", font='none 12')
xLabel.grid(column=0, row=6)
xEntry = tk.Entry(window, width=10)
xEntry.grid(columnspan=2, column=1, row=6)
yLabel = tk.Label(window, text="y: ", font='none 12')
yLabel.grid(column=0, row=7)
yEntry = tk.Entry(window, width=10)
yEntry.grid(columnspan=2, column=1, row=7)
zLabel = tk.Label(window, text="z: ", font='none 12')
zLabel.grid(column=0, row=8)
zEntry = tk.Entry(window, width=10)
zEntry.grid(columnspan=2, column=1, row=8)
# Rotation options
rxLabel = tk.Label(window, text="rx: ", font='none 12')
rxLabel.grid(column=0, row=9)
rxEntry = tk.Entry(window, width=10)
rxEntry.grid(columnspan=2, column=1, row=9)
ryLabel = tk.Label(window, text="ry: ", font='none 12')
ryLabel.grid(column=0, row=10)
ryEntry = tk.Entry(window, width=10)
ryEntry.grid(columnspan=2, column=1, row=10)
rzLabel = tk.Label(window, text="rz: ", font='none 12')
rzLabel.grid(column=0, row=11)
rzEntry = tk.Entry(window, width=10)
rzEntry.grid(columnspan=2, column=1, row=11)
entries = [xEntry, yEntry, zEntry, rzEntry, ryEntry, rxEntry]
deadspace3 = tk.Label(text="")
deadspace3.grid(columnspan=3, column=0, row=12)
btnMove = tk.Button(window, text="Move object", height=2, width=0,
bg="#bbbbbb", fg='white', justify=CENTER,
command=lambda: moveObject(entries))
btnMove.grid(column=1, row=13)
selectCallback = lambda: select_item(rdk, selectText, objName, entries)
btnSelect['command'] = selectCallback
EmbedWindow(window_title)
return window
# Close the window
def onClose(window: tk.Tk):
window.destroy()
quit(0)
def select_item(rdk: Robolink, selectText: tk.StringVar, objName: tk.Label,
entries: List[tk.Entry]):
def thread_btnSelect():
selectText.set("Waiting...")
item = rdk.ItemUserPick('Select an item', ITEM_TYPE_OBJECT)
if item.Valid():
global obj
obj = item
objName.set(item.Name())
updateObjectPosition(item, entries)
selectText.set("Select object")
# Prevent RoboDK from freezing
threading.Thread(target=thread_btnSelect).start()
def updateObjectPosition(item: Item, entries: List[tk.Entry]):
pose = item.Pose()
coords = Pose_2_KUKA(pose)
for entry, coord in zip(entries, coords):
entry.delete(0, END)
entry.insert(0, str(coord))
def moveObject(entries: tk.Entry):
global obj
if obj is None:
ShowMessage("No object selected")
return
try:
coords = getCoords(entries)
obj.setPose(KUKA_2_Pose(coords))
except Exception as err:
ShowMessage(str(err))
def getCoords(entries: List[tk.Entry]) -> list:
coords = [0] * 6
for i, entry in enumerate(entries):
coords[i] = float(entry.get())
return coords
if __name__ == "__main__":
main()
Using a tkinter.Variable such as tkinter.DoubleVar with your entries should fix this issue. You can also use tkinter.DoubleSpin for convenience.
x, y, z, rx, ry, rz = Pose_2_TxyzRxyz(item.Pose())
xVar = tk.DoubleVar(value=x)
xEntry = tk.Spinbox(window, textvariable=xVar, format="%.2f", from_=-9999999, to=9999999)
xVal = xVal.get()
I'm creating a frame which has many that are build vertically and I need a scrollbar to make them all visible. To do that I embedded my frame on a canvas.
The problem is that the widgets on the frame require more width that what the canvas provides as shown below
If I don't embed the frame on a canvas, then the widgets take the proper amount of width and are resized properly. I believe that the problem is the the canvas spans across 1 column whereas the widgets in the canvas require more than 2. I used `columnspan=2' on the canvas but the widgets on the embedded frame are still cut; they are just zoomed.
Is there a way to expand the width of the canvas according to the width they frame wants?
Here's an example code
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from PIL import ImageTk, Image
import os
# Method to make Label(Widget) invisible
def hide_frame(frame):
# This will remove the widget
frame.grid_remove()
# Method to make Label(widget) visible
def show_frame(frame, c, r):
# This will recover the widget
frame.grid(column=c, row=r)
def populate(frame):
'''Put in some fake data'''
for row in range(100):
tk.Label(frame, text="%s" % row, width=3, borderwidth="1",
relief="solid").grid(row=row, column=0)
t="Blah blah blah blah blah blah blah blah %s" %row
tk.Label(frame, text=t).grid(row=row+4, column=1)
#____________________________________________________________________________________________
#This will be the main window
window = tk.Tk()
#window.geometry('1500x1200')
window.attributes('-zoomed', True)
window.title("daq")
frame_main = Frame(window)
frame_main.place(rely=0.10, relx=0.0, relwidth=1.0)
#Create a tabcontrol
tabControl = ttk.Notebook(frame_main)
tabControl.grid(column=0, row=1)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Digitizer tab
tab_Digitizer = ttk.Frame(tabControl)
tabControl.add(tab_Digitizer, text=' Digitizer ')
digitizer_tab_dummy_label = Label(tab_Digitizer, text="")
digitizer_tab_dummy_label.grid(column=0, row=0)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Channel settings
lbl_channel_registers = Label(tab_Digitizer, text="Channel registers", font='bold')
lbl_channel_registers.grid(column=0, row=3, sticky=W)
frame_channel_registers = Frame(tab_Digitizer)
frame_channel_registers.grid(column=0, row=4)
btn_hide_channel_registers = Button(tab_Digitizer, text="Hide", fg="red", command=lambda: hide_frame(frame_channel_registers) )
btn_hide_channel_registers.grid(column=1, row=3)
btn_show_channel_registers = Button(tab_Digitizer, text="Show", fg="green", command=lambda: show_frame(frame_channel_registers, 0, 4))
btn_show_channel_registers.grid(column=2, row=3)
##Channel settings - PSD
def onFrameConfigure(event):
'''Reset the scroll region to encompass the inner frame'''
canvas.configure(scrollregion=canvas.bbox("all"))
def handle_user_scrolling(event):
canvas.yview_scroll(int(-event.delta/abs(event.delta)), "units")
def handle_scrollbar_scrolling(event):
canvas.configure(scrollregion=canvas.bbox("all"))
lbl_PSD_channel_registers = Label(frame_channel_registers, text="DPP-PSD registers")
lbl_PSD_channel_registers.grid(column=0, row=3, padx=5, sticky=W)
btn_hide_PSD_channel_registers = Button(frame_channel_registers, text="Hide", fg="red", command=lambda: [hide_frame(canvas), hide_frame(myscrollbar)] )
btn_hide_PSD_channel_registers.grid(column=1, row=3)
btn_show_PSD_channel_registers = Button(frame_channel_registers, text="Show", fg="green", command=lambda: [show_frame(canvas, 0, 4), show_frame(myscrollbar, 1, 4)])
btn_show_PSD_channel_registers.grid(column=2, row=3)
canvas = tk.Canvas(frame_channel_registers, borderwidth=1, background="#FF0000")
frame_PSD_channel_registers = Frame(canvas, background="#0000FF")
frame_PSD_channel_registers.grid(column=0, row=0, padx=25, sticky=W)
frame_PSD_channel_registers.bind("<MouseWheel>", handle_user_scrolling)
frame_PSD_channel_registers.bind("<Configure>", handle_scrollbar_scrolling)
myscrollbar=Scrollbar(frame_channel_registers ,orient="vertical", command=canvas.yview)
#canvas.configure(yscrollcommand=myscrollbar.set)
canvas.configure(scrollregion=canvas.bbox("all"))
myscrollbar.grid(column=1, row=4, sticky=NS)
canvas.grid(column=0, row=4, columnspan=3)
#frame_PSD_channel_registers = Frame(canvas, background="#0000FF")
#frame_PSD_channel_registers.grid(column=0, row=0, padx=25, sticky=W)
#frame_PSD_channel_registers.bind("<MouseWheel>", handle_user_scrolling)
#frame_PSD_channel_registers.bind("<Configure>", handle_scrollbar_scrolling)
canvas.create_window((0, 0), window=frame_PSD_channel_registers, anchor="nw")
canvas.configure(yscrollcommand=myscrollbar.set)
###### PSD channels settings
#Short gate
def short_gate_width_selection(event):
print ("Short gate width : " + str( entry_short_gate_width.get() ) + " " + var_short_gate_width_unit.get() )
pass
lbl_short_gate_width = Label(frame_PSD_channel_registers, text="Short gate width")
lbl_short_gate_width.grid(column=0, row=0, padx=25, sticky=W)
var_short_gate_width = IntVar(frame_PSD_channel_registers)
var_short_gate_width.set("15")
entry_short_gate_width = Entry(frame_PSD_channel_registers, width=10, textvariable=var_short_gate_width, exportselection=0)
entry_short_gate_width.grid(column=1, row=0, sticky=W)
opt_short_gate_width = ["samples", "ns"]
var_short_gate_width_unit = StringVar(frame_PSD_channel_registers)
var_short_gate_width_unit.set(opt_short_gate_width[0]) # default value
short_gate_width_unit = OptionMenu(frame_PSD_channel_registers, var_short_gate_width_unit, *opt_short_gate_width, command = short_gate_width_selection)
entry_short_gate_width.bind('<Return>', short_gate_width_selection)
short_gate_width_unit.grid(column=2, row=0, sticky=W)
#Long gate
def long_gate_width_selection(event):
print ("Long gate width : " + str( entry_long_gate_width.get() ) + " " + var_long_gate_width_unit.get() )
pass
lbl_long_gate_width = Label(frame_PSD_channel_registers, text="Long gate width")
lbl_long_gate_width.grid(column=0, row=1, padx=25, sticky=W)
var_long_gate_width = IntVar(frame_PSD_channel_registers)
var_long_gate_width.set("100")
entry_long_gate_width = Entry(frame_PSD_channel_registers, width=10, textvariable=var_long_gate_width, exportselection=0)
entry_long_gate_width.grid(column=1, row=1, sticky=W)
opt_long_gate_width = ["samples", "ns"]
var_long_gate_width_unit = StringVar(frame_PSD_channel_registers)
var_long_gate_width_unit.set(opt_long_gate_width[0]) # default value
long_gate_width_unit = OptionMenu(frame_PSD_channel_registers, var_long_gate_width_unit, *opt_long_gate_width, command = long_gate_width_selection)
entry_long_gate_width.bind('<Return>', long_gate_width_selection)
long_gate_width_unit.grid(column=2, row=1, sticky=W)
#Extras word options
def extras_word_options_selection(event):
if 'Counter' in var_extras_word_options_selection.get():
extras_word_options_step_counter.grid(column=2, row=22, sticky=W)
else:
extras_word_options_step_counter.grid_remove()
print ("Extras word options : " + var_extras_word_options_selection.get() )
pass
def extras_word_options_step_counter_selection(event):
print ("Step for trigger counter : ", var_extras_word_options_step_counter.get() )
pass
lbl_extras_word_options_selection = Label(frame_PSD_channel_registers, text="Extras word options")
lbl_extras_word_options_selection.grid(column=0, row=22, padx=25, sticky=W)
opt_extras_word_options_selection = ["[31:16] = Extended Time Stamp , [15:0] = Baseline * 4",
"[31:16] = Extended Time Stamp , [15:0] = Flags",
"[31:16] = Extended Time Stamp , [15:10] = Flags, [9:0] = Fine Time Stamp",
"[31:16] = Lost Trigger Counter , [15:0] = Total Trigger Counter",
"[31:16] = Positive Zero Crossing, [15:0] = Negative Zero Crossing",
"Fixed value = 0x12345678 (debug use only)."]
var_extras_word_options_selection = StringVar(frame_PSD_channel_registers)
var_extras_word_options_selection.set(opt_extras_word_options_selection[2]) # default value
extras_word_options_selection = OptionMenu(frame_PSD_channel_registers, var_extras_word_options_selection, *opt_extras_word_options_selection, command = extras_word_options_selection)
extras_word_options_selection.grid(column=1, row=22, sticky=W)
#This keeps the window open - has to be at the end
window.mainloop()
I am trying to make the following layout
tkinter layout
but the ID: label and the entry box are center left , and center right when then they should be next to each other , and they keep getting separated by the grid
I am also trying to use a for loop to make the number pad but im not sure how to make a new variable outside of the loops, and increment by 1 in the loop that creates the button
from tkinter import *
window = Tk()
#BOTTOM FRAME SECTION
bottomframe = Frame(window,bg="cyan", width =900, height = 100)
bottomframe.pack(fill=BOTH,side=BOTTOM)
button = Button(window,text="LOG IN")
button.pack(fill=BOTH,side=BOTTOM)
checkbutton = Checkbutton(window, text="Use pseudonym?")
checkbutton.pack(side=BOTTOM)
topframe = Frame(window,bg="red",width =900, height = 100)
topframe.pack(fill=BOTH,side=TOP)
label1 = Label(window, text="Majestic 12 Identifier")
label1.pack(side=TOP)
label2 = Label(window, text="ID")
label2.pack(side=LEFT)
label3 = Label(window,text="Enter keycode:")
label3.pack(side=TOP)
entry1 = Entry(window)
entry1.pack(side=LEFT)
#GRID SECTION
frame = Frame(window)
frame.pack(fill=BOTH,side=BOTTOM)
n = +1
for i in range(3):
Grid.rowconfigure(frame,i,weight=1)
Grid.columnconfigure(frame,i,weight=1)
for i in range(3):
b = Button(frame, text="%d" % (i+n))
for j in range(3):
b = Button(frame, text="%d" % (j+1))
b.grid(row=i, column=j,ipadx=2,ipady=2,padx=2,pady=2,sticky= W+E+N+S)
window.mainloop()
any help is welcome
Ok, I gave it a try. I played around a bit with the Frame objects. I deleted one, that was not needed. And I introduced topframe2 in order to make it possible for label2 and entry1 to be in the same row.
Watch carefully the parent of the various entries and labels. Not everything should get the window object as direct parent.
I am using expand and fill arguments - here I am basically applying what I just learned at Textbox not expanding with containing frame - TKinter and tkinter gui layout using frames and grid
from tkinter import *
window = Tk()
# BOTTOM FRAME SECTION
topframe = Frame(window, width=900, height=100)
topframe.pack(fill=BOTH, side=TOP)
label1 = Label(topframe, text="Majestic 12 Identifier")
label1.pack(side=TOP, fill=BOTH, expand=1)
topframe2 = Frame(topframe, width=900, height=100)
topframe2.pack(fill=BOTH, side=TOP)
label2 = Label(topframe2, text="ID")
label2.pack(side=LEFT)
entry1 = Entry(topframe2)
entry1.pack(side=LEFT, fill=X, expand=1)
label3 = Label(window, text="Enter keycode:")
label3.pack(side=TOP)
# GRID SECTION
frame = Frame(window)
frame.pack(fill=BOTH, side=TOP, expand=1)
n = +1
for i in range(3):
Grid.rowconfigure(frame, i, weight=1)
Grid.columnconfigure(frame, i, weight=1)
for i in range(3):
b = Button(frame, text="%d" % (i + n))
for j in range(3):
b = Button(frame, text="%d" % (j + 1))
b.grid(row=i, column=j, ipadx=2, ipady=2, padx=2, pady=2, sticky=W + E + N + S)
button = Button(window, text="LOG IN")
button.pack(fill=BOTH, side=BOTTOM)
checkbutton = Checkbutton(window, text="Use pseudonym?")
checkbutton.pack(side=BOTTOM)
if __name__ == '__main__':
window.mainloop()
I am very new in tkinter and python. Thats how my code looks:
import tkinter as tk
main = tk.Tk()
# Window size
main.geometry("400x700")
main.resizable(0, 0)
# Window position
w = main.winfo_reqwidth()
h = main.winfo_reqheight()
ws = main.winfo_screenwidth()
hs = main.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
main.geometry('+%d+%d' % (x, y))
fr1 = tk.Frame(main, borderwidth=2, relief="solid", bg = "#271ee3", width=400, height=50)
fr2 = tk.Frame(main, borderwidth=2, relief="solid", bg = "#0d9467", width=200, height=650)
fr3 = tk.Frame(main, borderwidth=2, relief="solid", bg = "#3e1854", width=200, height=650)
fr1.pack()
fr2.pack(side="left")
fr3.pack(side="right")
main.mainloop()
With this code I get the
following window
So far so good. The problem comes when i add this code:
# Label
l = tk.Label(fr2, text="Heyho")
l.grid(row=0, column=0)
Now it looks so
My goal is to get a window where i have in the first frame (fr1) a button that has the same geometry like fr1. In fr2 und fr3 I want to have severel labels among each other. My labels in fr2 und fr3 should have column 0 but ascending rows (0,1,2,3...). How can I do it??
It automatically resize Frame to Label's size so you don't see green background which is hidden behind label - and you see main window's gray background.
You can see it better if you add other longer label and red background in main window
If you add
fr2.grid_propagate(False)
then frame will keep its size
but you still have problem with grid which doesn't use full size of Frame and you can't center it or align to right.
If you add
fr2.grid_columnconfigure(0, weight=1)
then column 0 will try to use full size if there is no other columns, and label will be centered in cell
If you use
sticky='we'
in grid() for labels then they will fill cell
import tkinter as tk
main = tk.Tk()
# Window size
main.geometry("400x200")
main.resizable(0, 0)
main['bg'] = 'red'
# Window position
w = main.winfo_reqwidth()
h = main.winfo_reqheight()
ws = main.winfo_screenwidth()
hs = main.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
main.geometry('+%d+%d' % (x, y))
fr1 = tk.Frame(main, borderwidth=2, relief="solid", bg = "#271ee3", width=400, height=50)
fr2 = tk.Frame(main, borderwidth=2, relief="solid", bg = "#0d9467", width=200, height=650)
fr3 = tk.Frame(main, borderwidth=2, relief="solid", bg = "#3e1854", width=200, height=650)
fr1.pack()
fr2.pack(side="left")
fr3.pack(side="right")
fr2.grid_propagate(False)
fr2.grid_columnconfigure(0, weight=1)
l1 = tk.Label(fr2, text="Heyho")
l1.grid(row=0, column=0, sticky='we')
l2 = tk.Label(fr2, text="Hello World")
l2.grid(row=1, column=0, sticky='we')
main.mainloop()