I'm trying to make a menu but this just shows a blank GUI, what have i done wrong?
from tkinter import *
class GUI:
def __init__(self, master):
menu = Menu(master)
master.config(menu=menu)
submenu = Menu(menu)
menu.add_cascade(label="File", menu=submenu)
subMenu.add_command(label="Nothing", command=SayNothing)
subMenu.add_command(label="Exit", command=quit)
def SayNothing(self):
print("Nothing")
root = Tk()
app = GUI(root)
root.mainloop()
EDIT: I fixed a typo which now makes it display the 'File' but it doesn't show the submenus correctly
When mispellings and scoping are corrected, it works just fine:
from tkinter import *
class GUI:
def __init__(self, master):
menu = Menu(master)
master.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="Nothing", command=self.SayNothing)
subMenu.add_command(label="Exit", command=quit)
def SayNothing(self):
print("Nothing")
root = Tk()
app = GUI(root)
root.mainloop()
subMenu should be consistently spelled
command=self.SayNothing, not command=SayNothing
First off, submenu is case sensitive. So you must reference it as submenu not subMenu unless you re-define it. In addition, you defined SayNothing after you referenced it.
This should solve all your problems.
from tkinter import *
def SayNothing():
print("Nothing")
class GUI:
def __init__(self, master):
menu = Menu(master)
master.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="Nothing", command=SayNothing)
subMenu.add_command(label="Exit", command=quit)
root = Tk()
app = GUI(root)
root.mainloop()
Related
I have created a menu bar and a textbox, in the textbox I like to show the info in the variable that belongs to the chooice that been made in the menu.
But I can not figure out how.
Heres what I managed to put together by different guides on the web. Im verry new to python and Im still struggeling with the concept on objects and classes so any help at all will be greatly appriciated.
from tkinter import Tk, Frame, Menu
from tkinter import *
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("syntax explenation for shopfloor")
menubar = Menu(self.master)
self.master.config(menu=menubar)
syntaxMenu = Menu(menubar, tearoff=False)
submenu = Menu(syntaxMenu)
syntaxMenu.add_cascade(label='Math', menu=submenu, underline=0)
submenu.add_command(label="abs()", command=self.onSyntaxabs)
submenu.add_command(label="cos()", command=self.onSyntaxcos)
submenu.add_command(label="sin()", command=self.onSyntaxsin)
submenu.add_cascade(label="log()", command=self.onSyntaxlog)
submenu = Menu(syntaxMenu)
syntaxMenu.add_cascade(label='Inqurie', menu=submenu, underline=0)
submenu.add_command(label="inqiureText()", command=self.onSyntaxinquire)
menubar.add_cascade(label="Syntax", underline=0, menu=syntaxMenu)
def onSyntaxabs():
info="Convert to absolute value, abs(-10) will respond with 10."
def onSyntaxcos():
info="Returns cosinus value in decimal degrees"
def onSyntaxcos():
info="Returns cosinus value in decimal degrees"
def onSyntaxlog():
info="Returns the natural logarithm"
def onSyntaxinquire():
info="Creates a pop-up box that you can enter text in."
def main():
root = Tk()
root.geometry("500x600")
app = Example()
S = Scrollbar(root)
T = Text(root, height=20, width=60, bg="lightblue")
S.pack(side=RIGHT, fill=Y)
T.pack(side=LEFT, fill=BOTH)
T.pack(side=RIGHT, fill=BOTH)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
info=?
T.insert(END, info)
mainloop( )
if __name__ == '__main__':
main()
Here's a little push forward:
from tkinter import Tk, Frame, Menu, Scrollbar, Text
from tkinter import RIGHT, LEFT, BOTH, END, Y
from tkinter import StringVar
class Example(Frame):
def __init__(self, master):
super().__init__(master)
self.pack(fill=BOTH, expand=True)
self.initUI()
def initUI(self):
self.master.title("syntax explenation for shopfloor")
menubar = Menu(self.master)
self.master.config(menu=menubar)
syntaxMenu = Menu(menubar, tearoff=False)
submenu = Menu(syntaxMenu)
syntaxMenu.add_cascade(label='Math', menu=submenu, underline=0)
submenu.add_command(label="abs()", command=self.onSyntaxabs)
submenu.add_command(label="cos()", command=self.onSyntaxcos)
submenu.add_command(label="sin()", command=self.onSyntaxsin)
submenu.add_cascade(label="log()", command=self.onSyntaxlog)
submenu = Menu(syntaxMenu)
syntaxMenu.add_cascade(label='Inqurie', menu=submenu, underline=0)
submenu.add_command(label="inqiureText()", command=self.onSyntaxinquire)
menubar.add_cascade(label="Syntax", underline=0, menu=syntaxMenu)
S = Scrollbar(self) # Should probably be an instance member as well
self.text = Text(self, height=20, width=60, bg="lightblue")
S.pack(side=RIGHT, fill=Y)
self.text.pack(side=LEFT, fill=BOTH)
self.text.pack(side=RIGHT, fill=BOTH)
S.config(command=self.text.yview)
self.text.config(yscrollcommand=S.set)
self.setText("?")
def setText(self, text):
self.text.delete(1.0,END)
self.text.insert(END, text)
def onSyntaxabs(self):
self.setText("Convert to absolute value, abs(-10) will respond with 10.")
def onSyntaxsin(self):
self.setText("Returns sinus value in decimal degrees")
def onSyntaxcos(self):
self.setText("Returns cosinus value in decimal degrees")
def onSyntaxlog(self):
self.setText("Returns the natural logarithm")
def onSyntaxinquire(self):
self.setText("Creates a pop-up box that you can enter text in.")
def main():
root = Tk()
root.geometry("500x600")
app = Example(master=root)
app.mainloop()
if __name__ == '__main__':
main()
In general, I'd try to avoid importing all those symbols and just do something like
import tkinter as tk
then where you write Frame or RIGHT you'd use tk.Frame or tk.RIGHT.
Also, I moved all your widget creation inside of the class. So now your Text widget is a class member (self.text) and can be accessed and controlled easily from within the class -- all of your onSyntax___ methods call setText (another class method) which sets the Text widget's contents.
Hope it helps.
Thank you all for your input.
And I'll will continue to work with your post jedward.
I'll look in to Eclipse and Py Charm since I really need something like that.
When creating a second window using python 3.6 and tkinter, it is not responsible. I`m using os x 10.11.6.
In other systems such as Ubuntu, this code works.
from tkinter import *
class win2:
def __init__(self):
self.root = Tk()
self.root.mainloop()
class win1:
def __init__(self):
self.root = Tk()
self.button = Button(self.root)
self.button.bind('<Button-1>', self.buttonFunc)
self.button.pack()
self.root.mainloop()
def buttonFunc(self, event):
windows2 = win2()
if __name__ == "__main__":
window1 = win1()
It's a very bad idea to use Tk() more than once in your program. Use it to make the root window, and then use Toplevel() to make any additional windows.
def buttonFunc(self, event):
Toplevel(self.root)
That said, it still looks like you are trying to do something the hard way. Can you describe better what your end goal is?
To make a modal window (a popup) use code like this:
try: #python3 imports
import tkinter as tk
except ImportError: #python3 failed, try python2 imports
import Tkinter as tk
class Main(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
lbl = tk.Label(self, text="this is the main frame")
lbl.pack()
btn = tk.Button(self, text='click me', command=self.open_popup)
btn.pack()
def open_popup(self):
print("runs before the popup")
Popup(self)
print("runs after the popup closes")
class Popup(tk.Toplevel):
"""modal window requires a master"""
def __init__(self, master, **kwargs):
tk.Toplevel.__init__(self, master, **kwargs)
lbl = tk.Label(self, text="this is the popup")
lbl.pack()
btn = tk.Button(self, text="OK", command=self.destroy)
btn.pack()
# The following commands keep the popup on top.
# Remove these if you want a program with 2 responding windows.
# These commands must be at the end of __init__
self.transient(master) # set to be on top of the main window
self.grab_set() # hijack all commands from the master (clicks on the main window are ignored)
master.wait_window(self) # pause anything on the main window until this one closes
def main():
root = tk.Tk()
window = Main(root)
window.pack()
root.mainloop()
if __name__ == '__main__':
main()
This code works for me.
from tkinter import *
class win1:
def __init__(self):
root = Tk()
button = Button(root)
button.bind('<Button-1>', self.buttonFunc)
button.pack()
root.mainloop()
def buttonFunc(self, event):
window2 = win2()
class win2(win1):
def __init__(self):
top = Toplevel()
if __name__ == "__main__":
window1 = win1()
This is my Copy&Paste program:
from tkinter import *
import Pmw
class CopyTextWindow(Frame):
def __init__(self):
Frame.__init__(self)
Pmw.initialise()
self.pack(expand=YES, fill=BOTH)
self.master.title("ScrolledText Demo")
self.frame1=Frame(self, bg="White")
self.frame1.pack(expand=YES, fill=BOTH)
self.text1=Pmw.ScrolledText(self, text_width=25, text_height=12, text_wrap=WORD,
hscrollmode="static", vscrollmode="static")
self.text1.pack(side=LEFT, expand=YES, fill=BOTH, padx=5, pady=5)
options = ["Copy", "Paste"]
self.selectedOption = StringVar()
self.menu = Menu(self.frame1, tearoff=0)
for option in options:
self.menu.add_radiobutton( label=option, variable=self.selectedOption,
command=self.ExecuteOption)
self.text1.bind("<Button-3>", self.popUpMenu)
def popUpMenu(self, event):
self.menu.post(event.x_root, event.y_root)
def ExecuteOption(self):
if self.selectedOption.get()=="Copy":
self.CopiedText=self.text1.get(SEL_FIRST, SEL_LAST)
else:
self.text1.settext( self.text1.get()+self.CopiedText)
def main():
CopyTextWindow().mainloop()
if __name__=="__main__":
main()
In this program, I want to make a GUI, that in it you can copy and paste text that you have selected. when you press the right mouse button, a little menu with the Copy and Paste options.
The program opens up, but when I press the right mouse button, no menu appears. Python also doesn't complain with an error.
I need to understand my mistake in this code.
For a reason I ignore, the event doesn't seem to be triggered when the bind is on the Text or on the Frame, but it works when it's on the main window:
from tkinter import *
import Pmw
class CopyTextWindow(Frame):
def __init__(self, master=None):
# I've added a master option to pass to the frame
Frame.__init__(self, master)
Pmw.initialise()
self.pack(expand=YES, fill=BOTH)
self.master.title("ScrolledText Demo")
self.frame1=Frame(self, bg="White")
self.frame1.pack(expand=YES, fill=BOTH)
self.text1=Pmw.ScrolledText(self, text_width=25, text_height=12, text_wrap=WORD,
hscrollmode="static", vscrollmode="static")
self.text1.pack(side=LEFT, expand=YES, fill=BOTH, padx=5, pady=5)
options = ["Copy", "Paste"]
self.selectedOption = StringVar()
self.menu = Menu(self.frame1, tearoff=0)
for option in options:
self.menu.add_radiobutton( label=option, variable=self.selectedOption,
command=self.ExecuteOption)
def popUpMenu(self, event):
print("ok")
self.menu.post(event.x_root, event.y_root)
def ExecuteOption(self):
if self.selectedOption.get()=="Copy":
self.CopiedText=self.text1.get(SEL_FIRST, SEL_LAST)
else:
self.text1.settext( self.text1.get()+self.CopiedText)
def main():
# main window
root = Tk()
ctw = CopyTextWindow(root)
# bind on the main window
root.bind("<Button-3>", ctw.popUpMenu)
root.mainloop()
if __name__=="__main__":
main()
i have this program
class loginWindow():
def __init__(self, master):
self.master = master
self.frame = Frame(master)
master.title(u"Geometry Calc - Login")
Button(master, text="Login", command=self.login).pack()
def login(self):
self.newWindow = Toplevel(self.master)
main(self.newWindow)
self.master.withdraw()
class main():
def __init__(self, master):
# Nastavení nového okna
master.title(u"Geometry Calc") # Nadpis
master.geometry("695x935") # Rozmery v px
master.config(background="white")
master.resizable(width=FALSE, height=FALSE) # Zakážeme změnu rozměrů uživatelem - zatím..
menubar = Menu(master)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Konec", command=master.quit)
menubar.add_cascade(label="Soubor", menu=helpmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="O programu", command=self.createAbout)
menubar.add_cascade(label="Pomoc", menu=helpmenu)
master.config(menu=menubar)
canvas = Canvas(master, width=691, height=900)
canvas.pack(expand=1, fill=BOTH)
self.showImage(canvas, 347, 454, "geometry_table.jpg")
root = Tk()
app = loginWindow(root)
root.mainloop()
`
and i have this problem. When i run my program, i can see login window, when i hit login button I get window main, but window login is only withdrawed. So when i close window main my program still run. And i need make this. First run program main, but will be invisible or something. And i see only login window (maybe Toplevel). When i hit button login the window loginWindow will get destroy() and the window main will be visible
You can use Toplevel for login window and withdraw , deiconify methods to hide and show root window respectively.
Check the following code:
from Tkinter import *
class loginWindow(Toplevel):
def __init__(self, title, parent):
Toplevel.__init__(self, parent)
# Save parent reference to use it
self.parent = parent
self.parent.title(u"Geometry Calc - Login")
Button(self, text="Login", command=self.login).pack()
def login(self):
access = True # Used to test if a user can login.
if access:
# Close Toplevel window and show root window
self.destroy()
self.parent.deiconify()
else:
self.parent.quit()
class main(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.title(u"Geometry Calc") # Nadpis
self.geometry("695x935") # Rozmery v px
self.config(background="white")
self.resizable(width=FALSE, height=FALSE) # Zakážeme změnu rozměrů uživatelem - zatím..
menubar = Menu(self)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Konec", command=self.quit)
menubar.add_cascade(label="Soubor", menu=helpmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="O programu", command=self.createAbout)
menubar.add_cascade(label="Pomoc", menu=helpmenu)
self.config(menu=menubar)
canvas = Canvas(self, width=691, height=900)
canvas.pack(expand=1, fill=BOTH)
# Hide root window
self.withdraw()
# Lunch login window
loginWindow('Frame', self)
def createAbout(self):
pass
def quit(self):
self.destroy()
app = main()
app.mainloop()
If youn want to use 2 Toplevel windows for login and main app, root window should be hidden:
class loginWindow(Toplevel):
def __init__(self, title, parent):
Toplevel.__init__(self, parent)
...
def login(self):
if access:
# Close Toplevel window and lunch root window
self.destroy()
main()
class main(Toplevel):
def __init__(self, *args, **kwargs):
Toplevel.__init__(self, *args, **kwargs)
...
root = Tk()
root.withdraw()
loginWindow('title', root)
root.mainloop()
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())