Python | Popup widget in Kivy using .kv file
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
👉🏽 Kivy Tutorial – Learn Kivy with Examples.
Popup widget:
To use popup you must have to import :
from kivy.uix.popup import Popup
The Popup widget is used to create popups. By default, the popup will cover the whole “parent” window. When you are creating a popup, you must at least set a Popup.title and Popup.content.
Keep one thing in mind that the default size of a widget is size_hint=(1, 1). If you don’t want your popup to be on the full screen you must gave either size hints with values less than 1 (for instance size_hint=(.8, .8)) or deactivate the size_hint and use fixed size attributes.
Note: Popup is a special widget. Don’t try to add it as a child to any other widget. If you do, Popup will be handled like an ordinary widget and won’t be created hidden in the background, like:
Basic Approach:
1) import kivy
2) import kivyApp
3) import Widget
4) import Floatlayout
5) import Label
6) import popup
7) Set minimum version(optional)
8) Create widget class
9) Create Layout class :
10) create App class
9) create .kv file (name same as the app class):
1) create Widget
2) create popup
3) Give label to popup
4) create button to close popup
10) return Layout/widget/Class(according to requirement)
11) define popup function(Which shows the popup on press the button)
12) Run an instance of the class
Implementation of the Approach:
popup.py file
Python3
import kivy
from kivy.app import App
kivy.require( '1.9.0' )
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
class Widgets(Widget):
def btn( self ):
show_popup()
class Popups(FloatLayout):
pass
class MyApp(App):
def build( self ):
return Widgets()
def show_popup():
show = Popups()
popupWindow = Popup(title = "Popup Window" , content = show,
size_hint = ( None , None ), size = ( 200 , 200 ))
popupWindow. open ()
if __name__ = = "__main__" :
MyApp().run()
|
.kv file implementation:
Python3
<Widgets>:
Button:
text: "Press me"
on_release: root.btn()
<Popups>:
Label:
text: "You pressed the button"
size_hint: 0.6 , 0.2
pos_hint: { "x" : 0.2 , "top" : 1 }
Button:
text: "Close the popup"
size_hint: 1 , 0.4
pos_hint: { "x" : 0 , "y" : 0.1 }
|
Output:
When button press popup appears, click anywhere in the window except popup screen popup will disappear:
Last Updated :
26 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...