deconstructing basic Tk inter script - python-3.x

I need help in understanding how Tk inter works.I'm using the first example from the documents page which creates a simple window with 2 buttons.
Introduction to GUI programming with tkinter
Code:
from tkinter import Tk, Label, Button
class MyFirstGUI:
def __init__(self, master):
self.master = master
master.title("A simple GUI")
self.label = Label(master, text="This is our first GUI!")
self.label.pack()
self.greet_button = Button(master, text="Greet", command=self.greet)
self.greet_button.pack()
self.close_button = Button(master, text="Close", command=master.quit)
self.close_button.pack()
def greet(self):
print("Greetings!")
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()
Questions:
MyFirstGUI does not inherit from TK or Frame so how does it know of all the parameters (self.label,self.greet etc) one might find in the Tk class
We are passing a TK object to the variable root ( root = Tk() )
and passing that into MyFirstGUI class (my_gui = MyFirst GUI(root) )
.The only plausible explanation then, is that self.label and self.greet_button are "indeed" class variables to begin with and "become" labels ( and buttons ) once they are bound with functions such as Label(master,text="This is our first GUI!")
is my understanding correct ?
behram

So tkinter is just a library with classes inside of it, in this code you are importing the TK class, the Label class, and the Button class. When you use import statements at the top of your code, you are telling the computer to go fetch those files/functions and read them into the program. For example, if the TK class is say 100 lines of code, the statement
from tkinter import TK is equivalent to those 100 lines of code being in front of what you have written.
Now jumping to the creation of the UI itself, you create an instance of the TK class, and assign it to the variable root.
This root creates the outer window you will see when you run your UI, it holds the title, the min/max/close buttons in the top right corner, and determines the size of the window, along with a bunch of other features.
"root" is just a conventional name, it could be "potato" but as long as you know that is the foundation of your User Interface, that's what matters.
It won't be called too much outside of that first time you pass it into your class unless you're doing a lot of window manipulation.
From there, you are passing that root (window) to your MyFirstGUI object.
The __init__ function will run at the time of creation for any python class and the parameters for that function will be the parameters required to call the class. In this case, there are two parameters self, and master.
"self" is required as the first parameter of all functions inside a class so that the function knows the object it belongs to and so that it can access the class level variables available to it.
"master" has a default value of None so you could theoretically call MyFirstGUI() but in this case we are passing the root (window) as the master for the object MyFirstGUI(root).
At that point, because we are creating an instance of MyFirstGUI, __init__ fires and the first thing it does is sets self.master equal to the input of master so that it can be referenced anywhere in the object, expanding the scope beyond just the __init__ function.
From there, the function is arbitrarily defining variables that are scoped at the class level by using self. again so that these variables can be called from any part of this class.
self.label is just a name the original writer decided on, once again it could be self.macaroni as long as it makes sense to you that this is your label.
Then, because you have imported the Label class from tkinter, you are able to just refer to it as if it was already in your code. When you call these classes, they return the objects that are being set to your self.label so that you can refer to them later in the program.
If you check out the docs, you can see the Label and Button classes each have their own set of parameters available to them.
Common parameters include as you see "text" to show text that you'd like it to have, command to let a button know which function it should fire when clicked, "width" to determine the width of the widget on screen, and so on.
With the use of Default values, you don't always need to provide every single possible parameter to a call to create these objects.
Deciding what parameters to give comes down to practice and knowledge of the capabilities of each class in order to know which values you want to set and what are appropriate settings for them.
tldr:
Your import statements at the top allow you to use the classes at will, and your knowledge determines which parameters to send to each class. The docs are your friend!
I believe your understanding is correct. self.label is defined in the __init__ function by the programmer, and then assigned the widget object of a tkLabel by calling the class. From that point on, self.label is available anywhere inside the MyFirstGUI class to be manipulated as you see fit. For example, instead of the greet function printing out "Greetings!" you could change that print statement to self.label.set("Greetings!") so now your button click will change the label's text instead.
I hope this helped!

Related

Reload UI, Rather Than Recreating

import sys
import webbrowser
import hou
from PySide2 import QtCore, QtUiTools, QtWidgets, QtGui
# Calling UI File & Some Modification
class someWidget(QtWidgets.QWidget):
def __init__(self):
super(someWidget,self).__init__()
ui_file = 'C:/Users/XY_Ab/Documents/houdini18.5/Folder_CGI/someUI.ui'
self.ui = QtUiTools.QUiLoader().load(ui_file, parentWidget=self)
self.setParent(hou.qt.mainWindow(), QtCore.Qt.Window)
self.setFixedSize(437, 42)
self.setWindowTitle("Requesting For Help")
window_C = someWidget()
window_C.show()
So, I have created this small script that shows the UI, I have connected this to Houdini Menu Bar. Now The Problem is if I click the menu item multiple times it will create another instance of the same UI & the previous one stays back, What I want is something called "If Window Exist Delete It, Crate New One" sort of thing.
Can someone guide me? I am fairly new to python in Houdini and Qt so a little explanation will be hugely helpful. Also, why can't I use from PySide6 import?? Why do I have to use from PySide2?? Because otherwise Houdini is throwing errors.
For the same thing what used to do in maya is
# Check To See If Window Exists
if cmds.window(winID, exists=True):
cmds.deleteUI(winID)
Trying to do the same thing inside Houdini.
I don't have Maya or Houdini, so I can't help you too much.
According to https://www.sidefx.com/docs/houdini/hom/cb/qt.html
It looks like you can access Houdini's main window. The main reason the window is duplicated or deleted is how python retains the reference to window_C. You might be able to retain the reference to just show the same widget over and over again by accessing the main Houdini window.
In the examples below we are using references a different way. You probably do not need your code that has
self.setParent(hou.qt.mainWindow(), QtCore.Qt.Window)
Create the widget once and keep showing the same widget over and over.
import hou
# Create the widget class
class someWidget(QtWidgets.QWidget):
def __init__(self, parent=None, flags=QtCore.Qt.Window): # Note: added parent as an option
super(someWidget,self).__init__(parent, flags)
...
MAIN_WINDOW = hou.ui.mainQtWindow()
try:
MAIN_WINDOW.window_C.show()
except AttributeError:
# Widget has not been created yet!
# Save the widget reference to an object that will always exist and is accessible
# parent shouldn't really matter, because we are saving the reference to an object
# that will exist the life of the application
MAIN_WINDOW.window_C = someWidget(parent=MAIN_WINDOW)
MAIN_WINDOW.window_C.show()
To delete the previous window and create a new window.
import hou
# Create the widget class
class someWidget(QtWidgets.QWidget):
def __init__(self, parent=None, flags=QtCore.Qt.Window): # Note: added parent as an option
super(someWidget,self).__init__(parent, flags)
...
MAIN_WINDOW = hou.ui.mainQtWindow()
# Hide the previous window
try:
MAIN_WINDOW.window_C.close()
MAIN_WINDOW.window_C.deleteLater() # This is needed if you parent the widget
except AttributeError:
pass
# Create the new Widget and override the previous widget's reference
# Python's garbage collection should automatically delete the previous widget.
# You do not need to have a parent!
# If you do have a parent then deleteLater above is needed!
MAIN_WINDOW.window_C = someWidget() # Note: We do not parent this widget!
MAIN_WINDOW.window_C.show()
Another resource shows you can access the previous widget from the page level variable. https://echopraxia.co.uk/blog/pyqt-in-houdinimaya-basic This is possible, but seems odd to me. The module should only be imported once, so the page level variable "my_window" should never exist. However, it sounds like the Houdini plugin system either reloads the python script or re-runs the import. If that is the case every time you show a new window from the import of the script, you are creating a new window. If the previous window is not closed and deleted properly, Houdini could have an ever growing memory issue.
try:
my_window.close()
except (NameError, Exception):
pass # Normal python would always throw a NameError, because my_window is never defined
my_window = MyWindow()
#This is optional you can resize the window if youd like.
my_window.resize(471,577)
my_window.show()
PySide6
https://www.sidefx.com/docs/houdini/hom/cb/qt.html
The bottom of the page shows how to use PyQt5. The same would apply for PySide6. Houdini just happens to come with PySide2.

Add a QWidget inside a QFrame

I'm developing a desktop software using Python3 and QtDesigner for the Graphic User Interface.
My problem is the seguent: i'm trying to automate the creation of many QRadioButtons over a QFrame (The RadioButtons must stay inside the frame [as...children?]).
Now, i see that i can only create new widgets inside a Layout (e.g. "MyLayout.addWidget(QRadioButton")) and it's not possible to do something like "MyFrame.addWidget(QRadioButton)". I need these widgets inside the frame cause then i can place them in the correct position with "MyRB.move(X,Y)".
With QtDesigner is possible to place many Widgets (like RadioButtons) in a frame that has a 'broken layout' so i can choose X,Y coordinates but i need to create and place a variable number of those.
Is it possible to create Qwidgets inside a QFrame?
[EDIT]
according to musicamante's comment, i got that's a parent problem.
I tried to insert a Label and a RadioButton in the main window:
def __init__(self):
super().__init__()
uic.loadUi('DSS_GUI2.ui',self) # i load the GUI with QtDesigner
LB1 = QLabel('MyLabel',self)
RB1 = QRadioButton('MyRadioButton',self)
...
This very simple example works fine but when i try to add a Label through a function
def myFunction(self):
LB1 = QLabel('MyLabel')
LB1.setObjectName('LABEL_1')
LB1.setParent(self.myFrame)
the Widget is inserted but it is not visible, in fact adding this lines to check his presence
WidgetList = self.myFrame.findChildren(QLabel)
for item in WidgetList:
print(item.objectName())
i see in the console that the Label is there.
Do you know why it's not visible?
Try
def myFunction(self):
LB1 = self.sender()
LB1.QLabel('MyLabel')
LB1.setObjectName('LABEL_1')
LB1.setParent(self.myFrame)
You can call self.myFunction() in parent.
If you wanted to pass label, you could:
def myFunction(self, label):
LB1 = self.sender()
LB1.QLabel(label)
LB1.setObjectName(label)
LB1.setParent(self.myFrame)

Tkinter: pack()ing frames that use grid()

I am working on a UI for a data-display applet. I started with a tutorial and have since expanded it well beyond the scope of the tutorial, but some legacy bits remain from the tutorial that are now causing me difficulty. In particular relating to pack() and grid().
Following the tutorial I have defined a class Window(Frame) object, which I then declare as app = Window(root) where root = Tk(). Within the Window object is an initializing function def init_window(self), where my problems arise. Here is the relevant code in init_window():
def init_window(self):
self.master.title('Data Explorer') #changing the widget title
self.pack(fill=BOTH,expand=1) # allow widget to take full space of root
# Initializing a grid to place objects on
self.mainframe = Frame(root)
self.mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
self.mainframe.columnconfigure(0, weight = 1)
self.mainframe.rowconfigure(0, weight = 1)
self.mainframe.pack(pady = 10, padx = 10)
where the object self.mainframe contains a number of data selection dropdowns and buttons later on.
If I understand what this code is expected to do: it sets up the full window to be pack()ed with various frames. It then initializes a frame, self.mainframe, and within that frame initializes a grid(). Thus pack() and grid() do not collide. This setup was built by following the aforementioned tutorial.
This works correctly on my computer where I am developing the applet. However, when a collaborator compiles, they receive
_tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack
on the line self.mainframe.grid(...). I have replaced the mainframe.pack() command with a mainframe.place() command, but this has not resolved the issue (since his compile does not reach that point); I have not figured out a way to remove the self.pack() command without causing all other elements of my UI to vanish.
Can anyone help us understand what is going wrong? For reference, we are both using MacOS, and compiling with Python3. I can provide additional information as requested, within limits.
The error is telling you exactly what is wrong. You can't use grid on a widget in the root window when you've already used pack to manage a widget in the root window.
You wrote:
It then initializes a frame, self.mainframe, and within that frame initializes a grid()
No, that is not what your code is doing. It is not setting up a grid within the frame, it's attempting to use grid to add the widget to the root window.
First you have this line of code which uses pack on a widget in the root window:
self.pack(fill=BOTH,expand=1)
Later, you try to use grid for another window in the root window:
self.mainframe = Frame(root)
self.mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
The above isn't setting up a grid within self.mainframe, it's using grid to add the widget to the root window.
You need to use one or the other, you can't use both for different windows that are both direct children of the root window.
In other words, you're doing this:
self.pack(fill=BOTH,expand=1)
self.mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
but since both self and self.mainframe are a direct child of the root window, you can't do that. You need to either use pack for both:
self.pack(fill=BOTH,expand=1)
self.mainframe.pack(...)
... or grid for both:
self.grid(...)
self.mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )

how structure a python3/tkinter project

I'm developing a small application using tkinter and PAGE 4.7 for design UI.
I had designed my interface and generated python source code. I got two files:
gm_ui_support.py: here declare tk variables
gm_ui.py : here declare widget for UI
I'm wondering how this files are supposed to be use, one of my goals is to be able to change the UI as many times as I need recreating this files, so if I put my code inside any of this files will be overwritten each time.
So, my question is:
Where I have to put my own code? I have to extend gm_ui_support? I have to create a 3th class? I do directly at gm_ui_support?
Due the lack of answer I'm going to explain my solution:
It seems that is not possible to keep both files unmodified, so I edit gm_ui_support.py (declaration of tk variables and events callback). Each time I make a change that implies gm_ui_support.py I copy changes manually.
To minimize changes on gm_ui_support I create a new file called gm_control.py where I keep a status dict with all variables (logical and visual) and have all available actions.
Changes on gm_ui_support.py:
I create a generic function (sync_control) that fills my tk variables using a dict
At initialize time it creates my class and invoke sync_control (to get default values defined in control)
On each callback I get extract parameter from event and invoke logical action on control class (that changes state dict), after call to sync_control to show changes.
Sample:
gm_ui_support.py
def sync_control():
for k in current_gm_control.state:
gv = 'var_'+k
if gv in globals():
#print ('********** found '+gv)
if type(current_gm_control.state[k]) is list:
full="("
for v in current_gm_state.state[k]:
if len(full)>1: full=full+','
full=full+"'"+v+"'"
full=full+")"
eval("%s.set(%s)" % (gv, full))
else:
eval("%s.set('%s')" % (gv, current_gm_state.state[k]))
else:
pass
def set_Tk_var():
global current_gm_state
current_gm_control=gm_control.GM_Control()
global var_username
var_username = StringVar()
...
sync_control()
...
def on_select_project(event):
w = event.widget
index = int(w.curselection()[0])
value = w.get(index)
current_gm_control.select_project(value)
sync_state()
...

Adding items to a Listbox using Entries from another class

I have created two classes, one is in People.py (which will be the parent class) which contains a list box that can be populated by just opening a file and adding content to the list box line by line.
Another class is in Names.py (which I want it to be child class), which contains entries of first name, last name, and a combo box for titles that should (will implement once question/problem is answered) go into the list in the main window where the class is People. I am trying to use an OOP model. Right now, it's not fully OOP, but I will refactor the code later.
I have tried posting this code before but people are having trouble running it due to indentation problems, so I'm providing the links to the classes. In Dropbox Name Class and People Class:
Note: I'm running this in a Linux environment, so you may have to modify the file choosing line in the People class if using Windows (or another OS).
f = os.path.expanduser('~/Desktop')
Actually, you still have a problem of inconsistent use of tabs and spaces, which I solved, but maybe other people cannot solve it.
First of all, you should name your files/modules with lower cases (by convention, and you should follow it!). Then, in Names.py you are doing from Tkinter import * and then from Tkinter import Tk, which does not make any sense: with the first you are already importing Tk.
Your problem is the following:
People.people_list.insert(Tk.END, FirstName.get()) AttributeError:
'module' object has no attribute 'people_list'
In fact, you are trying to access an inexistent attribute of the module People called people_list, which is a local variable to some functions, from what I have been seeing.
If you want to fill a Listbox which is a property of some Toplevel A, with the input from another Toplevel B, you should pass a reference of the Toplevel A to B, maybe during its construction.
Here you have an example:
from tkinter import * # python 3
class Other(Toplevel):
"""Note that the constructor of this class
receives a parent called 'master' and a reference to another Toplevel
called 'other'"""
def __init__(self, master, other):
Toplevel.__init__(self, master)
self.other = other # other Toplevel
self.lab = Label(self, text="Insert your name: ")
self.lab.grid(row=0, column=0)
self.entry = Entry(self)
self.entry.grid(row=0, column=1)
# When you click the button you call 'self.add'
self.adder = Button(self, text='Add to Listbox', command=self.add)
self.adder.grid(row=1, column=1)
def add(self):
"""Using a reference to the other window 'other',
I can access its attribute 'listbox' and insert a new item!"""
self.other.listbox.insert("end", self.entry.get())
class Main(Toplevel):
"""Window with a Listbox"""
def __init__(self, master):
Toplevel.__init__(self, master)
self.people = Label(self, text='People')
self.people.grid(row=0)
self.listbox = Listbox(self)
self.listbox.grid(row=1)
if __name__ == "__main__":
root = Tk()
root.withdraw() # hides Tk window
main = Main(root)
Other(root, main) # passing a reference of 'main'
root.mainloop()
I noticed also that you are using 2 instance of Tk for each of your windows, which is bad. You should use just one instance of Tk for every application. If you want to use multiple windows, just use Toplevels, as I mentioned.
In general, your structure is not so good. You should start by creating simple good applications, and then pass to big ones once you grasp the basic concepts.

Resources