Home > Net >  Menu button position
Menu button position

Time:08-06

I have been trying to use Tkinter to make a window and then create buttons at the top left like most programs have, i.e. File, Edit, Select, View etc. I can create a button with text, and I've tried different ways to move the position of the button, but, for some reason, it's not working. If my understanding is correct, the top left position when using .grid should be (row=0, column=0). So, for verification purposes, I tried using (row=10, column=1) and the button is still at the same position. Please help!

from tkinter import *

root = Tk()
root.geometry("300x250")
root.title("D&D Tracker")

menubutton = Button(root, text="File", command=root.destroy)
menubutton.grid(row=10, column=1)

root.mainloop()

CodePudding user response:

This is from geeksforgeeks, but what you want is tkinter Menu widget:

# importing only  those functions 
# which are needed
from tkinter import * 
from tkinter.ttk import * 
from time import strftime
  
# creating tkinter window
root = Tk()
root.title('Menu Demonstration')
  
# Creating Menubar
menubar = Menu(root)
  
# Adding File Menu and commands
file = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='File', menu = file)
file.add_command(label ='New File', command = None)
file.add_command(label ='Open...', command = None)
file.add_command(label ='Save', command = None)
file.add_separator()
file.add_command(label ='Exit', command = root.destroy)
  
# Adding Edit Menu and commands
edit = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Edit', menu = edit)
edit.add_command(label ='Cut', command = None)
edit.add_command(label ='Copy', command = None)
edit.add_command(label ='Paste', command = None)
edit.add_command(label ='Select All', command = None)
edit.add_separator()
edit.add_command(label ='Find...', command = None)
edit.add_command(label ='Find again', command = None)
  
# Adding Help Menu
help_ = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Help', menu = help_)
help_.add_command(label ='Tk Help', command = None)
help_.add_command(label ='Demo', command = None)
help_.add_separator()
help_.add_command(label ='About Tk', command = None)
  
# display Menu
root.config(menu = menubar)
mainloop()

OUTPUT

You can use add_cascade method to have a menu inside a menu and add_checkbutton method for buttons with two states (like auto-start on some programs).

Regarding the tkinter grid, it always starts from the top left corner even if you change row/column value, you need to change padx and pady values to change it's position within the grid or use pack() instead.

  • Related