Python Tkinter, how to disable a button in a class? - python

I have seen many explanations of how to turn an enabled button disabled but not when classes are involved. The error here is in the line 'button_1.config...' and the error message is that button_1 is not defined. I think this is because it is in a different method but im not sure how to disable a button from a different method. any help is appreciated.
from tkinter import *
class menu:
def __init__(self, master):
self.master = master
button_1 = Button(self.master, text = 'test', command = self.correct).pack()
def correct(self):
button_1.config(state = DISABLED)
def window():
root = Tk()
menu(root)
root.mainloop()
if __name__ == '__main__':
window()

The button needs to be an instance variable, if you're accessing it between methods in the class. Just add self. in front of it. It's also going to need to be packed on a separate line, otherwise the instance variable self.button_1 will return None:
class menu:
def __init__(self, master):
self.master = master
self.button_1 = Button(self.master, text = 'test', command = self.correct)
self.button_1.pack()
def correct(self):
self.button_1.config(state = DISABLED)

Related

Creating a button in classes. Can someone help why this doesnt work

from tkinter import *
root = Tk()
def main():
Window1 = Window(root, "hello", "500x500",)
class Window:
def __init__(self, root, title, geometry,):
self.root = root
root.title(title)
root.geometry(geometry)
root.mainloop()
class Button(Window):
def __init__(self, message):
self.message = message
super().__init__(root,)
Button(root, text=message,).pack()
root.mainloop()
Button("HI")
main()
One of the two major issues I see is that your Button class is hiding the one that tkinter defines with the same name that would have been available via the from tkinter import *. The second one is that your Button shouldn't be derived from your Window class because subclassing implies there's is an "is a" relationship between the two classes — which is clearly not the case with them.
Below is an object-oriented way to do things that does work:
import tkinter as tk # PEP 8 recommends avoiding `import *`
def main():
root = tk.Tk()
window1 = Window(root, "hello", "500x500")
Button(root, "HI")
root.mainloop()
class Window:
def __init__(self, root, title, geometry):
self.root = root
root.title(title)
root.geometry(geometry)
class Button:
def __init__(self, parent, message):
self.message = message
tk.Button(parent, text=message).pack()
if __name__ == '__main__':
main()
There are a couple of issues.
Firstly, you're creating a subclass of Window called "Button". When you subclass something, it means that it will be of a similar type as it's parent (Window != Button). But more than that, when you define Button, you're actually hiding tkinter's button!
Second, you need to think about the event loop. When working with GUIs, you want to set everything up (where is the button, where are form elements, etc.) before running the mainloop (where possible). You're calling the root.mainloop function in each element, when you should only really call it once (and probably in your main() method).
So how to actually do it? You're code may look something like this
from tkinter import *
class Window:
def __init__(self, root, title, geometry, ):
self.root = root
root.title(title)
root.geometry(geometry)
def add_button(self, label):
btn = Button(self.root, text=label)
btn.pack(side='top')
def main():
root = Tk()
Window1 = Window(root, "hello", "500x500", )
Window1.add_button("Hi!")
root.mainloop()
if __name__ == "__main__":
main()
Here, the window has a method called "add_button", where you can add whatever button you want. Note that it is just creating a new Button object (the parent is "root") and then is "packing" it (feel free to read more about tk's layouts), which puts it in its place
I've also cleaned up the main function and called it under the classic 'if name == "main":' line.
import tkinter as tk
def main():
root = tk.Tk()
window1 = Window(root, "hello", "500x500")
Button(root, "Click me", 2, 2, 10, 5)
root.mainloop()
class Window:
def __init__(self, root, title, geometry):
self.root = root
root.title(title)
root.geometry(geometry)
class Button:
def __init__(self, parent, message, row, column, width, height,):
self.message = message
self.row = row
self.column = column
self.width = width
self.height = height
tk.Button(parent, text=message, height=height, width=width).grid(column=column, row=row)
if __name__ == '__main__':
main()
the grid function isnt working now lol

Open existing class with button in another class

I have a problem with opening existing class from button which is in another class.
I don't have any idea how to make it working because I know I should in function add (Toplevel) but it's also not working.
class na_dane(object):
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.frame.pack()
# CODE ........
def close_windows(self):
self.master.destroy()
# this code opens another window (class) which I have defined but not included here...
def new_window(self):
self.newWindow = tk.Toplevel.iconify(self.master)
self.app = sinus(self.newWindow)
# here is the main class where when I click button it should open na_dane Class
class menu(na_dane):
def __init__(self, master):
self.master = master
przycisk_Jednostkowo_Liniowa = tk.Button(
text="Funkcja jednostkowo-liniowa",
width=250,
height=2,
bg="blue",
fg="yellow"
).pack()
# HERE IS THE PROBLEM WHERE I TRY TO BIND BUTTON TO CLASS
przycisk_Jednostkowo_Liniowa.bind("<Button>", lambda e: na_dane(master))
przycisk_Jednostkowo_Liniowa.pack()
def main():
root = tk.Tk()
root.geometry("250x200")
root.title("GRUPA 3")
root['bg'] = '#FFFFFF'
app = menu(root)
root.mainloop()
if __name__ == '__main__':
main()
The problem seems to be that you attempt to pack przycisk_Jednostkowo_Liniowa in the same line as it is created. What this line of code is doing is creating a button with the characteristics described in your arguments, applying .pack() to it, then assigning the output of that .pack() execution to przycisk_Jednostkowo_Liniowa. Because .pack() doesn't have a return value, przycisk_Jednostkowo_Liniowa becomes None, so when you later attempt to bind a lambda to it, it doesn't recognize .bind() as a valid method. I tested the code with that .pack() removed and it worked for me.

"NameError[Command Name] is not defined" When Using Buttons in Tkinter

I'm trying to set up a list of checkbuttons from top to bottom in the GUI and add up the associated "onvalues" for each of the checkbuttons that are on.
My problem now is that for some reason my 'command' attribute in my 'calcbutton' is giving me a "Name 'calc_cost' is not defined" error.
I've added a bunch of imports that you see at the top of the code hoping that would solve the problem, to not much avail.
import tkinter as tk
from tkinter import *
from tkinter import Button
servicelist = ("Oil change","Lube job","Radiator flush","Transmission flush","Inspection","Muffler replacement","Tire rotation")
servicecost = (30,20,40,100,35,200,20)
a = 0
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def calc_cost(self):
print(a)
def init_window(self):
self.master.title("GUI")
self.pack(fill=BOTH, expand=1)
for i in range(len(servicelist)):
serviceButton = Checkbutton(self, text=servicelist[i], onvalue = servicecost[i], var = a)
serviceButton.place(x=0, rely = i*.1)
calcButton = tk.Button(self, text = "Calculate Cost", fg = "black", bg = "green", command = calc_cost)
calcButton.pack(side = "bottom")
root = Tk()
#size of the window
root.geometry("400x300")
app = Window(root)
root.mainloop()
The checkbuttons pop up and the GUI works for the most part besides the displaying of the 'calcbutton' as well as getting the "NameError: name 'calc_cost' is not defined"
Change command = calc_cost to command = self.calc_cost
self represents the instance of the class. By using the self keyword we can access the attributes and methods of the class in python.
It will give you this output

Hiding Tkinter root window while showing modal window

I have a TKinter-based application that attempts to manage settings for a game. Users may have multiple versions of this game installed, and in that case, I need to ask the user which installation they want to manage on startup. That part works well enough on its own; the selection dialog pops up after the main window is constructed, and runs modally.
However, due to differences between game versions, it would be useful if I could adapt the interface slightly for those cases. That, however, means I can't really build the main window until I know which installation I'm working on, so it's going to be blank until the user makes a choice.
I would like to hide the root window while this dialog is being shown, but calling withdraw on the root window simply causes the modal dialog to not be shown either - Python just ends up hanging with no CPU usage, and I can't figure out how to get around the problem without having to resort to a non-modal window (and a significantly different control flow, which I'd like to avoid).
Sample code exhibiting the problem and general code structure (Python 2.7):
from Tkinter import *
from ttk import *
class TkGui(object):
def __init__(self):
self.root = root = Tk()
self.root.withdraw()
selector = FolderSelection(self.root, ('foo', 'bar'))
self.root.deiconify()
print(selector.result)
class ChildWindow(object): #Base class
def __init__(self, parent, title):
top = self.top = Toplevel(parent)
self.parent = parent
top.title(title)
f = Frame(top)
self.create_controls(f)
f.pack(fill=BOTH, expand=Y)
def create_controls(self, container):
pass
def make_modal(self, on_cancel):
self.top.transient(self.parent)
self.top.wait_visibility() # Python will hang here...
self.top.grab_set()
self.top.focus_set()
self.top.protocol("WM_DELETE_WINDOW", on_cancel)
self.top.wait_window(self.top) # ...or here, if wait_visibility is removed
class FolderSelection(ChildWindow):
def __init__(self, parent, folders):
self.parent = parent
self.listvar = Variable(parent)
self.folderlist = None
super(FolderSelection, self).__init__(parent, 'Select folder')
self.result = ''
self.listvar.set(folders)
self.make_modal(self.cancel)
def create_controls(self, container):
f = Frame(container)
Label(
f, text='Please select the folder '
'you would like to use.').grid(column=0, row=0)
self.folderlist = Listbox(
f, listvariable=self.listvar, activestyle='dotbox')
self.folderlist.grid(column=0, row=1, sticky="nsew")
Button(
f, text='OK', command=self.ok
).grid(column=0, row=2, sticky="s")
self.folderlist.bind("<Double-1>", lambda e: self.ok())
f.pack(fill=BOTH, expand=Y)
def ok(self):
if len(self.folderlist.curselection()) != 0:
self.result = self.folderlist.get(self.folderlist.curselection()[0])
self.top.protocol('WM_DELETE_WINDOW', None)
self.top.destroy()
def cancel(self):
self.top.destroy()
TkGui()
It seems that in your case there is no difference, modal window or not. In fact, you just need to use the wait_window() method. According the docs:
In many situations, it is more practical to handle dialogs in a
synchronous fashion; create the dialog, display it, wait for the user
to close the dialog, and then resume execution of your application.
The wait_window method is exactly what we need; it enters a local
event loop, and doesn’t return until the given window is destroyed
(either via the destroy method, or explicitly via the window manager).
Consider follow example with nonmodal window:
from Tkinter import *
root = Tk()
def go():
wdw = Toplevel()
wdw.geometry('+400+400')
e = Entry(wdw)
e.pack()
e.focus_set()
#wdw.transient(root)
#wdw.grab_set()
root.wait_window(wdw)
print 'done!'
Button(root, text='Go', command=go).pack()
Button(root, text='Quit', command=root.destroy).pack()
root.mainloop()
When you click Go button, nonmodal dialog will appear, but code wil stop execution and the string done! will be displayed only after you close the dialog window.
If this is the behavior that you want, then here is your example in a modified form (I modified __init__ in TkGui and make_modal method, also added mainloop()):
from Tkinter import *
from ttk import *
class TkGui(object):
def __init__(self):
self.root = root = Tk()
self.root.withdraw()
selector = FolderSelection(self.root, ('foo', 'bar'))
self.root.deiconify()
print(selector.result)
class ChildWindow(object): #Base class
def __init__(self, parent, title):
top = self.top = Toplevel(parent)
self.parent = parent
top.title(title)
f = Frame(top)
self.create_controls(f)
f.pack(fill=BOTH, expand=Y)
def create_controls(self, container):
pass
def make_modal(self, on_cancel):
#self.top.transient(self.parent)
#self.top.wait_visibility() # Python will hang here...
#self.top.grab_set()
self.top.focus_set()
self.top.protocol("WM_DELETE_WINDOW", on_cancel)
self.top.wait_window(self.top) # ...or here, if wait_visibility is removed
class FolderSelection(ChildWindow):
def __init__(self, parent, folders):
self.parent = parent
self.listvar = Variable(parent)
self.folderlist = None
super(FolderSelection, self).__init__(parent, 'Select folder')
self.result = ''
self.listvar.set(folders)
self.make_modal(self.cancel)
def create_controls(self, container):
f = Frame(container)
Label(
f, text='Please select the folder '
'you would like to use.').grid(column=0, row=0)
self.folderlist = Listbox(
f, listvariable=self.listvar, activestyle='dotbox')
self.folderlist.grid(column=0, row=1, sticky="nsew")
Button(
f, text='OK', command=self.ok
).grid(column=0, row=2, sticky="s")
self.folderlist.bind("<Double-1>", lambda e: self.ok())
f.pack(fill=BOTH, expand=Y)
def ok(self):
if len(self.folderlist.curselection()) != 0:
self.result = self.folderlist.get(self.folderlist.curselection()[0])
self.top.protocol('WM_DELETE_WINDOW', None)
self.top.destroy()
def cancel(self):
self.top.destroy()
TkGui()
mainloop()
The code stops on line selector = FolderSelection(self.root, ('foo', 'bar')) and then continue after you close the dialog.

tkinter app adding a right click context menu?

I have a python-tkinter gui app that I've been trying to find some way to add in some functionality. I was hoping there would be a way to right-click on an item in the app's listbox area and bring up a context menu. Is tkinter able to accomplish this? Would I be better off looking into gtk or some other gui-toolkit?
You would create a Menu instance and write a function that calls
its post() or tk_popup() method.
The tkinter documentation doesn't currently have any information about tk_popup().
Read the Tk documentation for a description, or the source:
library/menu.tcl in the Tcl/Tk source:
::tk_popup --
This procedure pops up a menu and sets things up for traversing
the menu and its submenus.
Arguments:
menu - Name of the menu to be popped up.
x, y - Root coordinates at which to pop up the menu.
entry - Index of a menu entry to center over (x,y).
If omitted or specified as {}, then menu's
upper-left corner goes at (x,y).
tkinter/__init__.py in the Python source:
def tk_popup(self, x, y, entry=""):
"""Post the menu at position X,Y with entry ENTRY."""
self.tk.call('tk_popup', self._w, x, y, entry)
You associate your context menu invoking function with right-click via:
the_widget_clicked_on.bind("<Button-3>", your_function).
However, the number associated with right-click is not the same on every platform.
library/tk.tcl in the Tcl/Tk source:
On Darwin/Aqua, buttons from left to right are 1,3,2.
On Darwin/X11 with recent XQuartz as the X server, they are 1,2,3;
other X servers may differ.
Here is an example I wrote that adds a context menu to a Listbox:
import tkinter # Tkinter -> tkinter in Python 3
class FancyListbox(tkinter.Listbox):
def __init__(self, parent, *args, **kwargs):
tkinter.Listbox.__init__(self, parent, *args, **kwargs)
self.popup_menu = tkinter.Menu(self, tearoff=0)
self.popup_menu.add_command(label="Delete",
command=self.delete_selected)
self.popup_menu.add_command(label="Select All",
command=self.select_all)
self.bind("<Button-3>", self.popup) # Button-2 on Aqua
def popup(self, event):
try:
self.popup_menu.tk_popup(event.x_root, event.y_root, 0)
finally:
self.popup_menu.grab_release()
def delete_selected(self):
for i in self.curselection()[::-1]:
self.delete(i)
def select_all(self):
self.selection_set(0, 'end')
root = tkinter.Tk()
flb = FancyListbox(root, selectmode='multiple')
for n in range(10):
flb.insert('end', n)
flb.pack()
root.mainloop()
The use of grab_release() was observed in an example on effbot.
Its effect might not be the same on all systems.
I made some changes to the conext menu code above in order to adjust my demand and I think it would be useful to share:
Version 1:
import tkinter as tk
from tkinter import ttk
class Main(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
master.geometry('500x350')
self.master = master
self.tree = ttk.Treeview(self.master, height=15)
self.tree.pack(fill='x')
self.btn = tk.Button(master, text='click', command=self.clickbtn)
self.btn.pack()
self.aMenu = tk.Menu(master, tearoff=0)
self.aMenu.add_command(label='Delete', command=self.delete)
self.aMenu.add_command(label='Say Hello', command=self.hello)
self.num = 0
# attach popup to treeview widget
self.tree.bind("<Button-3>", self.popup)
def clickbtn(self):
text = 'Hello ' + str(self.num)
self.tree.insert('', 'end', text=text)
self.num += 1
def delete(self):
print(self.tree.focus())
if self.iid:
self.tree.delete(self.iid)
def hello(self):
print ('hello!')
def popup(self, event):
self.iid = self.tree.identify_row(event.y)
if self.iid:
# mouse pointer over item
self.tree.selection_set(self.iid)
self.aMenu.post(event.x_root, event.y_root)
else:
pass
root = tk.Tk()
app=Main(root)
root.mainloop()
Version 2:
import tkinter as tk
from tkinter import ttk
class Main(tk.Frame):
def __init__(self, master):
master.geometry('500x350')
self.master = master
tk.Frame.__init__(self, master)
self.tree = ttk.Treeview(self.master, height=15)
self.tree.pack(fill='x')
self.btn = tk.Button(master, text='click', command=self.clickbtn)
self.btn.pack()
self.rclick = RightClick(self.master)
self.num = 0
# attach popup to treeview widget
self.tree.bind('<Button-3>', self.rclick.popup)
def clickbtn(self):
text = 'Hello ' + str(self.num)
self.tree.insert('', 'end', text=text)
self.num += 1
class RightClick:
def __init__(self, master):
# create a popup menu
self.aMenu = tk.Menu(master, tearoff=0)
self.aMenu.add_command(label='Delete', command=self.delete)
self.aMenu.add_command(label='Say Hello', command=self.hello)
self.tree_item = ''
def delete(self):
if self.tree_item:
app.tree.delete(self.tree_item)
def hello(self):
print ('hello!')
def popup(self, event):
self.aMenu.post(event.x_root, event.y_root)
self.tree_item = app.tree.focus()
root = tk.Tk()
app=Main(root)
root.mainloop()
from tkinter import *
root=Tk()
root.geometry("500x400+200+100")
class Menu_Entry(Entry):
def __init__(self,perant,*args,**kwargs):
Entry.__init__(self,perant,*args,**kwargs)
self.popup_menu=Menu(self,tearoff=0,background='#1c1b1a',fg='white',
activebackground='#534c5c',
activeforeground='Yellow')
self.popup_menu.add_command(label="Cut ",command=self.Cut,
accelerator='Ctrl+V')
self.popup_menu.add_command(label="Copy ",command=self.Copy,compound=LEFT,
accelerator='Ctrl+C')
self.popup_menu.add_command(label="Paste ",command=self.Paste,accelerator='Ctrl+V')
self.popup_menu.add_separator()
self.popup_menu.add_command(label="Select all",command=self.select_all,accelerator="Ctrl+A")
self.popup_menu.add_command(label="Delete",command=self.delete_only,accelerator=" Delete")
self.popup_menu.add_command(label="Delete all",command=self.delete_selected,accelerator="Ctrl+D")
self.bind('<Button-3>',self.popup)
self.bind("<Control-d>",self.delete_selected_with_e1)
self.bind('<App>',self.popup)
self.context_menu = Menu(self, tearoff=0)
self.context_menu.add_command(label="Cut")
self.context_menu.add_command(label="Copy")
self.context_menu.add_command(label="Paste")
def popup(self, event):
try:
self.popup_menu.tk_popup(event.x_root, event.y_root, 0)
finally:
self.popup_menu.grab_release()
def Copy(self):
self.event_generate('<<Copy>>')
def Paste(self):
self.event_generate('<<Paste>>')
def Cut(self):
self.event_generate('<<Cut>>')
def delete_selected_with_e1(self,event):
self.select_range(0, END)
self.focus()
self.event_generate("<Delete>")
def delete_selected(self):
self.select_range(0, END)
self.focus()
self.event_generate("<Delete>")
def delete_only(self):
self.event_generate("<BackSpace>")
def select_all(self):
self.select_range(0, END)
self.focus()
ent=Menu_Entry(root)
ent.pack()
root.mainloop()
Important Caveat:
(Assuming the event argument that contains the coordinates is called "event"): Nothing will happen or be visible when you call tk_popup(...) unless you use "event.x_root" and "event.y_root" as arguments. If you do the obvious of using "event.x" and "event.y", it won't work, even though the names of the coordinates are "x" and "y" and there is no mention of "x_root" and "y_root" anywhere within it.
As for the grab_release(..), it's not necessary, anywhere. "tearoff=0" also isn't necessary, setting it to 1 (which is default), simply adds a dotted line entry to the context menu. If you click on it, it detaches the context menu and makes it its own top-level window with window decorators. tearoff=0 will hide this entry. Moreover, it doesn't matter if you set the menu's master to any specific widget or root, or anything at all.

Categories

Resources