Custom Closable Tab in Kivy - python

I am trying to implement a custom closable tab header in kivy.
What I did was combine a class:TabbedPanelHeader object with a custom class:CloseButton object. Both of these widgets are inside a class:BoxLayout, side-by-side.
However, once I add this into a class:TabbedPanel object, nothing shows up..
I am not sure how to move forward and would greatly appreciate all the help!
Below is the relevant part of the code.
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.graphics import *
from kivy.uix.tabbedpanel import TabbedPanelHeader
class CloseButton(ButtonBehavior, Image):
def __init__(self, **kwargs):
super(CloseButton, self).__init__(**kwargs)
self.source = 'atlas://data/images/defaulttheme/close'
self.size_hint_x = .2
def on_press(self):
self.source = 'atlas://data/images/defaulttheme/checkbox_radio_off'
def on_release(self):
self.source = 'atlas://data/images/defaulttheme/checkbox_radio_off'
## do the actual closing of the tab
class ClosableTabHeader(BoxLayout):
def __init__(self, **kwargs):
super(ClosableTabHeader, self).__init__(**kwargs)
self.size = (100, 30)
self.size_hint = (None, None)
self.canvas.before.add(Color(.25, .25, .25))
self.canvas.before.add(Rectangle(size=(105, 30)))
self.add_widget(TabbedPanelHeader(background_color=(.65, .65, .65, 0), text='testing'))
self.add_widget(CloseButton())
if __name__ == '__main__':
from kivy.app import App
class TestApp(App):
def build(self):
return ClosableTabHeader()
TestApp().run()

Here is some code which comes close to achieve what you are trying to achieve
from kivy.app import App
from kivy.animation import Animation
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelHeader
from kivy.factory import Factory
from kivy.lang import Builder
class CloseableHeader(TabbedPanelHeader):
pass
class TestTabApp(App):
def build(self):
return Builder.load_string('''
TabbedPanel:
do_default_tab: False
FloatLayout:
BoxLayout:
id: tab_1_content
Label:
text: 'Palim 1'
BoxLayout:
id: tab_2_content
Label:
text: 'Palim 2'
BoxLayout:
id: tab_3_content
Label:
text: 'Palim 3'
CloseableHeader:
text: 'tab1'
panel: root
content: tab_1_content.__self__
CloseableHeader:
text: 'tab2'
panel: root
content: tab_2_content.__self__
CloseableHeader:
text: 'tab3'
panel: root
content: tab_3_content.__self__
<CloseableHeader>
color: 0,0,0,0
disabled_color: self.color
# variable tab_width
text: 'tabx'
size_hint_x: None
width: self.texture_size[0] + 40
BoxLayout:
pos: root.pos
size_hint: None, None
size: root.size
padding: 3
Label:
id: lbl
text: root.text
BoxLayout:
size_hint: None, 1
orientation: 'vertical'
width: 22
Image:
source: 'tools/theming/defaulttheme/close.png'
on_touch_down:
if self.collide_point(*args[1].pos) :\
root.panel.remove_widget(root); \
''')
if __name__ == '__main__':
TestTabApp().run()
It is based on https://github.com/kivy/kivy/blob/master/examples/widgets/tabbed_panel_showcase.py

Related

Kivy - Calling a pulsing method from one class to another

I have the following classes in my kivy app, and i would like to call the blink method in my mainApp class. The start pulsing and blink methods enable the MainWindow background to pulse. However it's not working inside the MainWindow class and i need to call it in my mainApp class. Commented out (build method in mainApp) is what i tried, which results to the error Exception: Invalid instance in App.root. My python file:
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.core.window import Window
from kivymd.app import MDApp
from kivy.uix.image import Image
from kivy.animation import Animation
from kivy.clock import Clock
from kivy.properties import ColorProperty
from kivy.uix.popup import Popup
from kivy.uix.floatlayout import FloatLayout
from plyer import filechooser
data = ""
class MainWindow(Screen):
def analyze_data(self):
global data
data = self.ids.user_input.text
data = analyze(data)
animated_color = ColorProperty()
pulse_interval = 4
def blink(self):
x = Clock.schedule_once(self.start_pulsing, 5)
return x
def start_pulsing(self, *args):
d = self.pulse_interval / 2
anim = Animation(animated_color=(69/255, 114/255, 147/255, 1), duration=d) + Animation(animated_color=(1, 1, 1, 1), duration=d)
anim.repeat = True
anim.start(self)
class OutputScreen(Screen):
def on_enter(self, *args):
self.ids.output_label.text = data
class mainApp(MDApp):
def __init__(self):
super().__init__()
def choose_file(self):
try:
filechooser.open_file(on_selection = self.handle_selection)
except:
pass
def handle_selection(self,selection):
global path
selection_ls = selection[0]
path = selection_ls
#print(path)
def change_screen(self,screen):
screemanager = self.root.ids['screenmanager']
screemanager.current = screen
def change(self):
self.change_screen('output')
def back(self):
self.change_screen('main')
'''
def build(self):
x = MainWindow().blink()
return x'''
and my kv file:
#:import utils kivy.utils
GridLayout:
cols:1
ScreenManager:
id: screenmanager
MainWindow:
id: main
name: 'main'
OutputScreen:
id: output
name: 'output'
<MainWindow>:
BoxLayout:
orientation:'vertical'
MDBottomNavigation:
panel_color: utils.get_color_from_hex("#ffffff")
MDBottomNavigationItem:
name:'analytics'
text:'analytics'
icon:'account-circle'
FloatLayout:
size: root.width, root.height
canvas.before:
Color:
rgba: root.animated_color
Rectangle:
pos:self.pos
size:self.size
TextInput:
multiline:True
id: user_input1
pos_hint:{"x" : 0.05, "top" : 0.9}
size_hint: 0.9, 0.37
Label:
markup: True
id:input_label
pos_hint:{"x" : 0, "top":1}
size_hint: 1 ,0.08
font_size : 32
bold: True
canvas.before:
Color:
rgb: utils.get_color_from_hex("01121c")
Rectangle:
size: self.size
pos: self.pos
Button:
pos_hint:{"top" : 0.51, "x" : 0.05}
size_hint: (None,None)
width : 150
height : 40
font_size : 23
text:'Submit'
on_press: root.analyze_data()
on_release: app.change()
Button:
pos_hint:{"top":0.42, "x":0.05}
size_hint: (None,None)
width : 150
height : 40
font_size : 23
text:'Upload'
on_release:app.choose_file()
Button:
id:'info_button'
pos_hint:{"top":0.47, "x":0.8}
size_hint: (None,None)
width : 50
height : 22
font_size : 23
text:'i'
on_release:root.analytics_info()
<OutputScreen>:
ScrollView:
GridLayout:
cols:1
MDIconButton:
icon:'arrow-left'
pos_hint:{'top':1,'left':1}
size_hint: 0.1,0.1
user_font_size : '64sp'
on_release: app.back()
Label:
id: output_label
multiline:True
text_size: self.width, None
size_hint: 1, None
height: self.texture_size[1]
color: 0,0,0,1
padding_x: 15
Any help will be much appreciated.
The build() method of an App should return a Widget that will become the root of the App. But your build() method returns a ClockEvent (the return from Clock.schedule_once()). Try changing your build() method to:
def build(self):
x = MainWindow()
x.blink()
return x
Since you do not call Builder.load_file(), I assume that your kv file is named main.kv, and therefore will get loaded automatically. If that is true, then you do not need a build() method at all. Instead add an on_start() method to your mainApp class, like this:
def on_start(self):
self.root.ids.main.blink()

Kivy Python IDs problems

I was using my main class as widget and was passing IDs from kv file to python without problems.
Now changed it to a screen as I need to switch between 2 screens but now I cant access the IDs declared in kv file. I get error - 'MainScreen'object has no attribute 'labINFO' - (this is the first label id I am trying to modify.)
Here are parts of py and kv files
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
class GSMNosScreen(Screen):
def gsmclose(self, obj):
Clock.schedule(self.startgetTemps,dataInterval)
BoilerApp.sm.current = 'main'
class MainScreen(Screen):
....
....
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
self.labINFO.text = "Waiting for Pic..."
self.labM1.text = str(b1Min)
self.labM2.text = str(b2Min)
sm = ScreenManager() #transition=NoTransition()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(GSMNosScreen(name='gsmnos'))
class BoilerApp(App):
def build(self):
self.title = 'Boiler Monitor'
return sm
if __name__ == "__main__":
from kivy.core.window import Window
Window.fullscreen = True
app = BoilerApp()
app.run()
KV file
<GSMNosScreen>:
labN1: labN1
size_hint: .5, .5
auto_dismiss: False
title: "GSM Numbers" # <<<<<<<<
separator_height: 0 # <<<<<<<<
GridLayout:
cols: 1
size: root.width, root.height
MyTLab:
id:labN1
font_size: 20
text: "Number 1 : ..."
MyBut:
text: "Close"
font_size: 20
size_hint: .2, .2
on_press: gsmclose()
<MainScreen>
labM1: labM1
labM2: labM2
labM3: labM3
labM4: labM4
labM5: labM5
labINFO: labINFO
labDT: labDT
GridLayout:
cols: 1
size: root.width, root.height
MyTLab:
text: "Monitor"
underline: True
size_hint: .5, .2
BoxLayout:
orientation: "horizontal"
size_hint_y: .2
MySTLab:
color: 0.8,.2,.2,0.7
text: "Min °C"
size_hint_x: 1.5
font_size: 25
MyMLab:
id: labM1
text: "50"
MyMLab:
id: labM2
text: "50"
MyMLab:
id: labM3
text: "50"
MyMLab:
id: labM4
text: "50"
BoxLayout:
orientation: "horizontal"
#cols:2
size_hint_y: .1
Label:
id: labDT
color: 0,1,0.5,0.8
text: "Starting ...."
font_size: sp(20)
size_hint_x: .3
Label:
id: labINFO
color: 0,1,0.5,0.8
text: "...."
font_size: sp(20)
size_hint_x: .7
I believe the problem is that the kv file has not been loaded yet when the lines:
sm = ScreenManager() #transition=NoTransition()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(GSMNosScreen(name='gsmnos'))
are executed.
Try moving the above lines into the build() method of the App:
class BoilerApp(App):
def build(self):
self.title = 'Boiler Monitor'
sm = ScreenManager() # transition=NoTransition()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(GSMNosScreen(name='gsmnos'))
return sm
The kv file (if it is named boiler.kv) is loaded before the build() mehod is called.

How do I define what happens when user enter's text in TextInput and presses enter in Kivy?

I am trying to create a simple Chatbot application UI using Kivy and Python but I'm stuck at the very first stage.
How do I access the TextInput widget inside the BoxLayout to fetch it's contents?
I read that the function on_text_validate() is called whenever you press 'Enter' on the TextInput. However this code down below doesn't seem to be functioning.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import Screen, ScreenManager, FadeTransition
from kivy.uix.scrollview import ScrollView
from kivy.properties import StringProperty
from kivy.lang import Builder
Builder.load_string('''
#:import AnchorLayout kivy.uix.anchorlayout
#:import Layout kivy.uix.layout
<ChatBotScreen>:
BoxLayout:
orientation: 'vertical'
ScrollView:
Label:
size_hint_y: None
height: self.texture_size[1]
text_size: self.width, None
botOutput: root.botOutput
ScrollView:
Label:
size_hint_y: None
height: self.texture_size[1]
text_size: self.width, None
userInput: root.userInput
TextInput:
id: ti_userinput
multiline: False
''')
class ChatBotScreen(Screen):
userInput = StringProperty()
botOutput = StringProperty()
def on_text_validate(self):
text_input_userInput = self.ids['ti_userinput'].text
self.ids['ti_userinput'].text = ''
print(text_input_userInput)
def UserInput(self):
pass
def BotOutput(self):
pass
sm = ScreenManager(transition=FadeTransition())
sm.add_widget(ChatBotScreen(name='mainchat'))
class MyApp(App):
def build(self):
return sm
Please guide me.
The problem in your case is that on_text_validate is not a method of the Screen class, but of TextInput, so you will never call on_text_validate of the ChatBotScreen class, what you can do is invoke that method from the on_text_validate event of the TextInput:
Builder.load_string('''
#:import AnchorLayout kivy.uix.anchorlayout
#:import Layout kivy.uix.layout
<ChatBotScreen>:
BoxLayout:
orientation: 'vertical'
ScrollView:
Label:
size_hint_y: None
height: self.texture_size[1]
text_size: self.width, None
botOutput: root.botOutput
ScrollView:
Label:
size_hint_y: None
height: self.texture_size[1]
text_size: self.width, None
userInput: root.userInput
TextInput:
id: ti_userinput
multiline: False
on_text_validate: root.on_text_validate()
''')
class ChatBotScreen(Screen):
userInput = StringProperty()
botOutput = StringProperty()
def on_text_validate(self):
text_input_userInput = self.ids['ti_userinput'].text
self.ids['ti_userinput'].text = ''
print(text_input_userInput)
sm = ScreenManager(transition=FadeTransition())
sm.add_widget(ChatBotScreen(name='mainchat'))
class MyApp(App):
def build(self):
return sm

Extremely oversized/large buttons inside Kivy Screen class

For the sake of brevity I'll explain my problem before posing the code. Here it goes:
I have a Screen class in Kivy that holds two widgets, a GridLayout and an Image. The latter is fine, but the buttons are extremely oversized:
And here's my main.py:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.factory import Factory
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image
from kivy.config import Config
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
import configparser
Builder.load_file('kv\MainMain.kv')
#read configurations
config = configparser.RawConfigParser()
config.read('config.ini')
#read config values
width = config.getint('Default', 'MAX_WINDOW_WIDTH')
height = config.getint('Default', 'MAX_WINDOW_HEIGHT')
border = config.getint('Default', 'BORDERLESS')
#apply config values
Config.set('graphics','width', width)
Config.set('graphics', 'height', height)
Config.set('graphics', 'borderless', border)
Config.set('input', 'mouse', 'mouse,multitouch_on_demand')
#create screen manager
class ScreenManager(ScreenManager):
pass
#create background widget
class BackGround(Image):
pass
#image buttons
class MainButtons(GridLayout):
pass
#create main screen:
class MainScreen(Screen):
pass
#create main app
class MainMainApp(App):
def build(self):
return MainScreen()
#register class
Factory.register(MainScreen, cls=MainScreen)
#run
if __name__ == '__main__':
MainMainApp().run()
And here's my kv file:
<ScreenManager>:
id: screen_manager
MainScreen:
id: main_screen
name: 'MainScreen'
manager: screen_manager
ReadScreen:
id: read_screen
name: 'ReadScreen'
manager: screen_manager
<MainScreen>:
BackGround:
id: back_ground
source: 'images\\app_background.jpg'
size: root.width, root.height
MainButtons:
cols: 1
pos: root.width / 2 - 100, root.height / 4
size: 20, 10
Button:
id: button_read
text: "Read"
on_press: root.callback_read()
Button:
id: button_add
text: "Add"
Button:
id: button_manage
text: "Manage"
I'm really swamped on this one. Thanks for your help.
You can use size_hint for this.
Here is an example
The pyhton file:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen,ScreenManager
Builder.load_file("my.kv")
class MainButtons(GridLayout):
pass
class MainScreen(Screen):
pass
class MainMainApp(App):
def build(self):
self.sm = ScreenManager()
self.sm.add_widget(MainScreen(name="main"))
return self.sm
if __name__ == '__main__':
MainMainApp().run()
and kivy file:
<MainScreen>:
MainButtons:
cols: 1
rows: 4
Label:
font_size: "40sp"
text: "Something"
Button:
size_hint: (1,0.1)
text: "Read"
Button:
size_hint: (1,0.1)
text: "Add"
Button:
size_hint: (1,0.1)
text: "Manage"
And output will be:
And if you want the buttons to be smaller in width, you add ´size_hint_x: None´ to your kv file, like this.
<MainScreen>:
MainButtons:
cols: 1
rows: 4
Label:
font_size: "40sp"
text: "Something"
Button:
size_hint: (1,0.1)
size_hint_x:None
text: "Read"
Button:
size_hint: (1,0.1)
size_hint_x:None
text: "Add"
Button:
size_hint: (1,0.1)
size_hint_x:None
text: "Manage"
Output will now be:

Kivy: Turning an App into a widget

I have built a Kivy GUI using the 'App' class that is designed to load a file using a file chooser and make it into a list. I have now learned that my whole chunk of code needs to be converted to a widget so that it can be integrated into an existing GUI scaffold. I am not sure how to go about 'widget-ifying' my code. Any help would be appreciated.
Below is my main.py file:
from kivy.app import App
from kivy.uix.accordion import Accordion, AccordionItem
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.uix.popup import Popup
from kivy.uix.button import Button
import os
from kivy.uix.widget import Widget
from kivy.uix.scrollview import ScrollView
from kivy.graphics import *
from kivy.properties import ObjectProperty
class OptionMenu(GridLayout):
loadfile = ObjectProperty(None)
savefile = ObjectProperty(None)
text_input = ObjectProperty(None)
def dismiss_popup(self):
self._popup.dismiss()
def show_load(self):
content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9))
self._popup.open()
def load(self, path, filename):
with open(os.path.join(path, filename[0])) as stream:
self.text_input.text = stream.read()
self.dismiss_popup()
def show_save(self):
content = SaveDialog(save=self.save, cancel=self.dismiss_popup)
self._popup = Popup(title="Save file", content=content,
size_hint=(0.9, 0.9))
self._popup.open()
def save(self, path, filename):
with open(os.path.join(path, filename), 'w') as stream:
stream.write(self.text_input.text)
self.dismiss_popup()
class GraphMenu(GridLayout):
pass
class UnnamedMenu(GridLayout):
pass
class LoadDialog(FloatLayout):
load = ObjectProperty(None)
cancel = ObjectProperty(None)
class SaveDialog(FloatLayout):
save = ObjectProperty(None)
text_input = ObjectProperty(None)
cancel = ObjectProperty(None)
class MainController(FloatLayout):
pass
class MainApp(App):
def build(self):
rt = MainController()
return rt
Factory.register('Main', cls=MainController)
Factory.register('LoadDialog', cls=LoadDialog)
Factory.register('SaveDialog', cls=SaveDialog)
if __name__ == '__main__':
MainApp().run()
Here is my main.kv file:
#kivy 1.0
<OptionMenu>
cols: 2
row:10
Button:
size_hint_y: 0.05
text: "Input File"
on_release: self.parent.show_load()
Button:
size_hint_y:0.05
text:"Save File"
on_release:self.parent.show_save()
TextInput:
id: text_input
text:''
RstDocument:
text: text_input.text
show_errors: True
<MainController>
BoxLayout:
orientation: 'horizontal'
Accordion:
size_hint_x: 0.3
orientation: 'vertical'
AccordionItem:
title:'Options'
OptionMenu:
id: 'AppOpt'
AccordionItem:
title:'Config'
UnnamedMenu:
id:ConfigTab
AccordionItem:
title:'Graph'
GraphMenu:
id:GraphTab
FloatLayout:
size_hint_x: 0.7
Label:
<scroller>
<LoadDialog>:
BoxLayout:
size: root.size
pos: root.pos
orientation: "vertical"
FileChooserListView:
id: filechooser
BoxLayout:
size_hint_y: None
height: 10
Button:
text: "Cancel"
on_release: root.cancel()
Button:
text: "Load"
on_release: root.load(filechooser.path, filechooser.selection)
<SaveDialog>:
text_input: text_input
BoxLayout:
size: root.size
pos: root.pos
orientation: "vertical"
FileChooserListView:
id: filechooser
on_selection: text_input.text = self.selection and self.selection[0] or ''
TextInput:
id: text_input
size_hint_y: None
height: 30
multiline: False
BoxLayout:
size_hint_y: None
height: 30
Button:
text: "Cancel"
on_release: root.cancel()
Button:
text: "Save"
on_release: root.save(filechooser.path, text_input.text)
I don't understand the question, your App does nothing special and all the functionality is in the MainController widget. What more separation do you need than that?
Factory.register('Main', cls=MainController)
Factory.register('LoadDialog', cls=LoadDialog)
Factory.register('SaveDialog', cls=SaveDialog)
Also, these Factory lines are unnecessary, widgets automatically register themselves.

Categories