How to get tkinter menubar label Value? - python

I have looked a lot but can`t find the answer, below is an example:
Menu.add_command(label='abc',command=callback)
How can I get this 'abc' for variable?

You can use entrycget() and pass to it the "label" option.
Here is a short example to demonstrate how it works:
import tkinter as tk
def callback(menu):
x= menu.entrycget(0, "label")
print(x) # This will print "abc" in your Terminal
root = tk.Tk()
menu_bar = tk.Menu(root)
file_menu = tk.Menu(menu_bar, tearoff=False)
file_menu.add_command(label="abc", command=lambda: callback(file_menu))
menu_bar.add_cascade(label="File", menu=file_menu)
root.config(menu=menu_bar)
root.mainloop()

I solved ur problem. Try this:
from tkinter import *
def callback(menu):
for index in range(0,1): print( menu.entrycget(0, "label"))
def callback1(menu1):
for index in range(1, 2): print( menu1.entrycget(1, "label"))
def callback2(menu):
for index in range(2,3): print( menu.entrycget(2, "label"))
def callback3(menu):
for index in range(3,4): print( menu.entrycget(3, "label"))
def callback4(menu):
for index in range(4,4): print( menu.entrycget(4, "label"))
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=lambda: callback(filemenu))
filemenu.add_command(label="Open", command=lambda: callback1(filemenu))
filemenu.add_command(label="Save", command=lambda: callback2(filemenu))
filemenu.add_command(label="Save as...", command=lambda: callback3(filemenu))
filemenu.add_command(label="Close", command=None)
root.config(menu=menubar)
root.mainloop()

Related

Tkinter Scrollable Text, the slider doesn't appear

I'm try to create scroll bar in "notepad(Program name)" but when i run my program it don't show
scrollbar in window .......................................................................
.....................................................................
from tkinter import *
SIDE_R = RIGHT
windows = Tk()
windows.title("NotePad")
windows.minsize(width=60, height=80)
windows.config()
frame = Frame(windows)
# Menu bar
# # File
menubar = Menu(windows)
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="close")
file.add_separator()
file.add_command(label="Exit", command=windows.quit)
menubar.add_cascade(label="File", menu=file)
# # Edit
edit = Menu(menubar, tearoff=0)
edit.add_separator()
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Cute")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=edit)
# # Help
helps = Menu(menubar, tearoff=0)
helps.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
# Create place to write a text
text = Text(windows)
text.focus()
text.grid(pady=0.5, padx=10)
# Creating Scale
scroll = Scrollbar(windows, orient=VERTICAL,)
scroll.grid(row=0, column=1, sticky=NS+SE)
text.config(yscrollcommand=scroll.set)
scroll.config(command=text.yview)
windows.config(menu=menubar)
windows.mainloop()

file system in tkinter(see,edit,remove)

I want to create some app in tkinter , the app is food organizer,
I have a problem to connect files to def(function) and control them there.
I mean I want to control the options: edit, remove, read, create.
I know I need to do something with function and 'command'
but have a problem with that.
from tkinter import *
import os
import files
from PIL import ImageTk , Image
def editfiles():
filewin1=Toplevel(root)
label= Label(filewin1, font=("ariel") , text="Choose order",fg="blue")
label.pack()
button=Button(filewin1, text="start edit")
button.pack(side=LEFT)
filewin1.wm_geometry("400x400")
chk_state = BooleanVar()
chk_state.set(True)
chk = Checkbutton(filewin1, text='File1', var=chk_state)
chk.pack(side=LEFT)
def create():
filewin2=Toplevel(root)
button = Button(filewin2 , font=("algerian") , text="create new order", bg="gray")
button.pack()
filewin2.wm_geometry("400x400")
def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
button.pack()
filewin.wm_geometry("400x400")
def remove():
filewin3 = Toplevel(root)
label= Label(filewin3, font=("ariel") , text="Choose order",fg="red")
label.pack()
button = Button(filewin3, text="remove")
button.pack(side=LEFT)
filewin3.wm_geometry("400x400")
chk_state = BooleanVar()
chk_state.set(True)
chk = Checkbutton(filewin3, text='File1', var=chk_state)
chk.pack(side=LEFT)
def just_see():
filewin5=Toplevel(root)
label=Label(filewin5, text="Orders list",font=("algerian"),fg="green")
label.pack()
button = Button(filewin5, text="Detiles")
button.pack(side=LEFT)
filewin5.wm_geometry("400x400")
chk_state = BooleanVar()
chk_state.set(True)
chk = Checkbutton(filewin5, text='File1', var=chk_state)
chk.pack(side=LEFT)
root = Tk()
root.title("F-order system Ltd")
root.wm_geometry("480x480")
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="All orders", command=just_see)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_separator()
editmenu.add_command(label="New order", command=create)
editmenu.add_command(label="Edit order", command=editfiles)
editmenu.add_command(label="Remove order", command=remove)
menubar.add_cascade(label="Edit", menu=editmenu)
root.config(menu=menubar)
C = Canvas(root, bg="blue", height=250, width=300)
filename = PhotoImage(file = 'C:\\Users\\PycharmProjects\\pythonProject1\\app.png')
background_label = Label(root, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
lblnum=Label(root, font=("david"), text="Food organizer" , height=1)
lblnum.pack()
root.iconphoto(False, PhotoImage(file= 'C:\\Users\\PycharmProjects\\pythonProject1\\icon.png'))
root.mainloop() ```
From what I have understood, I believe you want something like this (I wrote this small example just to show a possible approach)
from tkinter import *
import os
class App:
def __init__(self):
self.root=Tk()
self.dir='sample'
head_label=Label(self.root,text='Files')
head_label.pack()
self.listbox=Listbox(self.root)
self.listbox.pack()
for file in os.listdir(self.dir):
self.listbox.insert(END,file.split('.')[0])
new_button=Button(self.root,text='new',command=self.new)
new_button.pack(side='left')
edit_button=Button(self.root,text='edit',command=self.edit)
edit_button.pack(side='left')
edit_button=Button(self.root,text='remove',command=self.remove)
edit_button.pack(side='left')
self.root.mainloop()
def _popup(self):
def on_submit():
self.val=entry.get()
pop.destroy()
self.val=None
pop=Toplevel(self.root)
desc_label=Label(pop,text='Enter the value')
desc_label.pack()
entry=Entry(pop)
entry.pack()
sub_button=Button(pop,text='Submit',command=on_submit)
sub_button.pack()
self.root.wait_window(pop)
return self.val
def edit(self):
file=self.listbox.get(self.listbox.curselection())
os.system(os.path.join(self.dir,f'{file}.txt'))
def remove(self):
file=self.listbox.get(self.listbox.curselection())
os.remove(os.path.join(self.dir,f'{file}.txt'))
self.listbox.delete(self.listbox.get(0,END).index(file))
def new(self):
self._popup()
self.filename=os.path.join(self.dir,f'{self.val}.txt')
if self.val:
with open(self.filename,'w+') as file:
file.write('')
file.close()
self.listbox.insert(END,self.val)
if __name__=='__main__':
App()

why giving a tab master window and adding it to tk.notebook() result as the tab was given notebook as a master window

I'm currently a noob to tkinter as i made this code. so kindly ignore any foolishness if found.
import tkinter as tk
from tkinter import ttk
from tkinter import Menu
win=tk.Tk()
win.title('Tabs GUI')
tab_control=ttk.Notebook(win)
tab1=ttk.Frame(tab_control)
tab_control.add(tab1,text='Tab 1')
tab_control.grid()
tab2=ttk.Frame(win) #1
tab_control.add(tab2,text='Tab 2')
menuBar = Menu(tab1) #2
win.config(menu=menuBar)
# Add menu items
fileMenu = Menu(menuBar, tearoff=0)
fileMenu.add_command(label="New")
fileMenu.add_separator()
fileMenu.add_command(label="Exit")
menuBar.add_cascade(label="File", menu=fileMenu)
# Add another Menu to the Menu Bar and an item
helpMenu = Menu(menuBar, tearoff=0)
helpMenu.add_command(label="About")
menuBar.add_cascade(label="Help", menu=helpMenu)
ttk.Label(tab2, text="Choose a number:").grid(column=0, row=0)
numberChosen = ttk.Combobox(tab2, width=8)
numberChosen['values'] = (1, 2, 4, 42, 100)
numberChosen.grid(column=0, row=1)
numberChosen.current(0)
chVarDis = tk.IntVar()
check1 = tk.Checkbutton(tab2, text="Disabled", variable=chVarDis, state='disabled')
check1.select()
check1.grid(column=0, row=2, sticky=tk.W)
chVarUn = tk.IntVar()
check2 = tk.Checkbutton(tab2, text="UnChecked", variable=chVarUn)
check2.deselect()
check2.grid(column=1, row=2, sticky=tk.W )
win.mainloop()
now the first problem is that on #1 i gave 'tab2' master window i.e 'win', then added it to the notebook but it acts like i gave it notebook() as a master window because 'tab1' and 'tab2' are functioning same. And the second problem is why 'combobox' is auto-focused when i open 'tab2'. and the same goes for Menu() #2, i've given it parent tab1 yet it is displayed in top level window win

Using .get() within tkinter ScrolledFrame

I am trying to achieve grabbing par02_1 using .get(). I have success writing the rest of the .txt file but my program is not grabbing my gui entry lines. I'm guessing this has something to do with the association self, and the scrollable section, etc. but I can't track this one down. Any help is appreciated.
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import time
root = Tk()
# GUI Window
root.title("Outfile Automation")
# Gui Future Menu Logic
def future01():
print("Future Command 01")
# GUI Main Menu
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New Script...", command=future01)
subMenu.add_separator()
subMenu.add_command(label="Exit Program", command=future01)
helpMenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpMenu, command=future01)
helpMenu.add_command(label="Instruction Manual", command=future01)
helpMenu.add_command(label="Software Version: A0.003")
##Scrollbar
class VerticalScrolledFrame(Frame):
def __init__(self, parent, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
# create a canvas object and a vertical scrollbar for scrolling it
vscrollbar = Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
canvas = Canvas(self, bd=0, highlightthickness=0,
yscrollcommand=vscrollbar.set)
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=canvas.yview)
# reset the view
canvas.xview_moveto(0)
canvas.yview_moveto(0)
# create a frame inside the canvas which will be scrolled with it
self.interior = interior = Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior,
anchor=NW)
# track changes to the canvas and frame width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner frame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the canvas's width to fit the inner frame
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the inner frame's width to fill the canvas
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
if __name__ == "__main__":
class AutoApp(Tk):
def __init__(self, *args, **kwargs):
root = Tk.__init__(self, *args, **kwargs)
self.frame = VerticalScrolledFrame(root)
self.frame.pack()
self.label = Label(text="")
self.label.pack()
self.par02_1 = StringVar()
title_1 = Label(self.frame.interior, text="Device IP (DHCP)", fg="blue", font="Verdana 10 underline")
title_1.pack()
label_1 = Label(self.frame.interior, text="Device 01")
label_1.pack()
entry_1 = Entry(self.frame.interior, textvariable=self.par02_1)
entry_1.pack()
outFile = open('CSC.txt', 'wt')
outFile.write("[Script Header]\nDebugStrings=on\nAbortOnError=on\nConcurrentSectionLimit=230\n"
"//23 Devices if necessary""\n\n[Variables]""\n"
+ (self.par02_1.get()) + "\n\n"
"[Device01]\nConnect=tcp |proc01|\nRunAsSingleTransaction=on\nEthernetDHCPHost "
+ (self.par02_1.get()) + "EthernetCurrentConnectionInfo\n")
outFile.close()
def muser():
feedback_1 = Label(root, text="Creating Script...").pack()
feedback_2 = Label(root, text="Script Complete!").pack()
time.sleep(2)
return
# GUI Buttons
mbutton = Button(root, text="Create Script", command=muser, fg="black", bg='green')
mbutton.pack()
app = AutoApp()
app.mainloop()
Hello thank you both for your guidance as I learn proper syntax. I have a long way to go but you both helped point me in the right direction so I can get my program online. I stripped this down to the basics and will implement a variation of the following architecture in my actual code.
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import time
root = Tk()
# GUI Window
root.title("Outfile Automation")
# Gui Future Menu Logic
def future01():
print("Future Command 01")
# GUI Main Menu
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New Script...", command=future01)
subMenu.add_separator()
subMenu.add_command(label="Exit Program", command=future01)
helpMenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpMenu, command=future01)
helpMenu.add_command(label="Instruction Manual", command=future01)
helpMenu.add_command(label="Software Version: A0.003")
par02_1 = StringVar()
title_1 = Label(root, text="Device IP (DHCP)", fg="blue", font="Verdana 10 underline")
title_1.pack()
label_1 = Label(root, text="Device 01")
label_1.pack()
entry_1 = Entry(root, textvariable=par02_1)
entry_1.pack()
root.mainloop()
template = """[Script Header]\nDebugStrings=on\nAbortOnError=on\nConcurrentSectionLimit=230\n//23 Devices if necessary
\n\n[Variables]\n{}\n\n[Device01]\nConnect=tcp |proc01|\nRunAsSingleTransaction=on\nEthernetDHCPHost\nEthernetCurrentConnectionInfo\n"""
outFile = open('CSC.txt', 'wt')
outFile.write(template.format(par02_1.get()).rstrip())
outFile.close()
root.mainloop()

Tkinter dropdown Menu with keyboard shortcuts?

I would like to have a Dropdown Menu in Tkinter, that includes the shortcut key associated with this command. Is this possible?
How would I also add the underline under a certain character, to allow for Alt-F-S (File->Save)?
import tkinter as tk
import sys
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
menubar = tk.Menu(self)
fileMenu = tk.Menu(menubar, tearoff=False)
menubar.add_cascade(label="File", underline=0, menu=fileMenu)
fileMenu.add_command(label="Exit", underline=1,
command=quit, accelerator="Ctrl+Q")
self.config(menu=menubar)
self.bind_all("<Control-q>", self.quit)
def quit(self, event):
print("quitting...")
sys.exit(0)
if __name__ == "__main__":
app = App()
app.mainloop()
Maybe
from tkinter import *
import tkinter.filedialog as filed
root = Tk()
root.title("My Python Tkinter Application")
root.minsize(800,600)
def openfile():
fn = filed.askopenfilename(filetypes=[("Text Files","*.txt")], title="Open File")
f = open(fn, "r").read()
print(f)
def init():
menu = Menu(root)
filemenu = Menu(menu)
filemenu.add_command(label="Open (⌘O)", command=openfile)
menu.add_cascade(label="File", menu=filemenu)
root.config(menu=menu)
def key():
print("Key Pressed: "+repr(event.char))
root.bind("<Key>", key)
In this code press ctrl+e to exit the programmme
from tkinter import *
class MainApp:
def __init__(self, root):
self.root = root
self.menubar = Menu(self.root)
self.fileMenu = Menu(self.menubar, tearoff=False)
self.menubar.add_cascade(label="File", menu=self.fileMenu)
self.fileMenu.add_command(label="Exit", accelerator="Ctrl+E")
self.root.config(menu=self.menubar)
self.root.bind_all("<Control-e>", lambda event: self.root.quit())
self.root.mainloop()
if __name__ == "__main__":
MainApp(Tk())

Categories

Resources