I'm using kivy and I am trying to make a program to help me remember the super saiyans transformations. I wanted the buttons to be pictures instead of words. So here is the code I used to make the button a picture:
self.Goku = Button(background_normal = '106-1060675_goku-base-form-png-clipart (1).png')
self.Goku.bind(on_press = self.SonGoku)
self.add_widget(self.Goku)
When I runned the code to see what it looks like, I saw that one of the picture was to big and one to small. So I tried to resize the picture by adding size = ("10, 10") but it didn't work. I tried the same thing with size_hint, but it had the same result. Nothing moved. I looked at some documentations about the button and adding pictures to kivy but it didn't help much. Here's the entire code:
import kivy
from kivy.app import App
from kivy.graphics import *
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
class main(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 4
self.Goku = Button(background_normal = '106-1060675_goku-base-form-png-clipart (1).png', size_hint = (1, 0.5))
self.Goku.bind(on_press = self.SonGoku)
self.add_widget(self.Goku)
self.Vegeta = Button(background_normal = 'vegeta-png-clip-art.png', size_hint = (1, 1))
self.Vegeta.bind(on_press = self.PrinceVegeta)
self.add_widget(self.Vegeta)
def SonGoku(self, instance):
self.cols = 1
self.remove_widget(self.Goku)
self.remove_widget(self.Vegeta)
self.NormalGoku = Button(text = "Base form")
self.add_widget(self.NormalGoku)
self.SSJGoku = Button(text = "Super saiyan")
self.add_widget(self.SSJGoku)
self.SSJ2Goku = Button(text = "Super saiyan 2")
self.add_widget(self.SSJ2Goku)
def PrinceVegeta(self, instance):
self.cols = 1
self.remove_widget(self.Goku)
self.remove_widget(self.Vegeta)
self.NormalVegeta = Button(text = "Base form")
self.add_widget(self.NormalVegeta)
self.SSJVegeta = Button(text = "Super saiyan")
self.add_widget(self.SSJVegeta)
self.SSJ2Vegeta = Button(text = "Super saiyan 2")
self.add_widget(self.SSJ2Vegeta)
class Saiyan(App):
def build(self):
return main()
if __name__ == "__main__":
Saiyan().run()
Help would be appreciated. Feel free to ask any question. Thanks in advance.
One way of doing it would be to draw the image on the buttons canvas. the attributes "allow_stretch" and "keep_ratio" are used to fill the entire button size.
from kivy.uix.image import Image
Then:
self.Goku = Button(size_hint=(None, None), size=(120,120))
with self.Goku.canvas:
Image(source='vegeta-png-clip-art.png', size=self.Goku.size, pos=self.Goku.pos, allow_stretch=True, keep_ratio=False)
self.add_widget(self.Goku)
In case you are not setting the size explicitly for the button you need to bind the size attribute to a method in order to resize the image.
example:
class main(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 4
self.Goku = Button()
with self.Goku.canvas:
self.Goku_img = Image(source='vegeta-png-clip-art.png', size=self.Goku.size, pos=self.Goku.pos, allow_stretch=True, keep_ratio=False)
self.Goku.bind(size=self.adjust_size)
self.add_widget(self.Goku)
...
def adjust_size(self, instance, value):
self.Goku_img.size = value
I hope this is a suitable approach for you.
Related
What I want to do is take input from kivy.uix.textinput.TextInput() and show it on the screen.
I am new to gui Programming and I think it is an easy task.
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
class MyWindowApp(App):
def __init__(self):
super(MyWindowApp, self).__init__()
self.lbl = Label(text='Read Me!')
self.inp = TextInput(multiline=False,
size_hint =(1, 0.05),
pos_hint = {"x":0, "y":0.05})
def build(self):
self.inp.bind(on_text_validate=self.on_enter)
#self.bt1.bind(on_press=self.clk)
layout = FloatLayout()
layout.orientation = 'vertical'
layout.add_widget(self.lbl)
layout.add_widget(self.inp)
return layout
def on_enter(self,value):
print(value)
def clk(self, obj):
print ('input')
x = input()
self.lbl.text = x
window = MyWindowApp()
window.run()
when i run the code, I get the regular output output.
when I type say "hello world" in the textbox, this is the output:
<kivy.uix.textinput.TextInput object at 0x03F5AE30>
I do not get what I typed.
please suggest what should I do
Modify the following ...
def on_enter(self, value):
print(value.text)
I am trying to make tambola coin picker with Python and Kivy and I am new to kivy.
Here, I created gridlayout buttons from 1 to 90. I want to change the color of particular button in gridlayout when its number is picked. I am facing issues to update gridlayout with new colored button. Here I am attaching my code. screenshot
#!/usr/bin/python
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import Color
import random
coins = random.sample(range(1,91), 90)
#print(coins)
picked_coins=[]
current_coin=0
#print(picked_coins)
class Housie(FloatLayout):
def __init__(self,**kwargs):
super(Housie,self).__init__(**kwargs)
self.title = Label(text="Housie Coin Picker",font_size = 50,size_hint=(1, .55),pos_hint={'x':0, 'y':.45})
self.main_label = Label(text = "Click PICK NUMBER", size_hint=(1, .60),pos_hint={'x':0, 'y':.35})
self.picked_ones = Label(text = "picked_coins", size_hint=(1, .40),pos_hint={'x':0, 'y':.40})
self.help_button = Button(text = "PICK NUMBER", size_hint=(.3, .1),pos_hint={'x':.65, 'y':.1},on_press = self.update)
self.add_widget(self.title)
self.add_widget(self.main_label)
self.add_widget(self.picked_ones)
self.add_widget(self.help_button)
self.add_widget(self.userinterface())
def userinterface(self):
self.layout = GridLayout(cols = 10,size_hint=(.50, .50))
for i in range(1,91):
self.layout.add_widget(Button(background_color=(1,0,0,1),text =str(i)))
return self.layout
def update(self,event):
for coin in coins:
if coin not in picked_coins:
current_coin=coin
picked_coins.append(coin)
self.main_label.text = str(coin)
for i in self.layout.children:
if i.text == str(coin):
#What to do Here?
break
self.picked_ones.text = "Picked coins = {}".format(" ".join(str(sorted(picked_coins))))
class app1(App):
def build(self):
return Housie()
if __name__=="__main__":
app1().run()
You can bind a method to each Button like this:
def userinterface(self):
self.layout = GridLayout(cols = 10,size_hint=(.50, .50))
for i in range(1,91):
self.layout.add_widget(Button(background_color=(1,0,0,1),text=str(i), on_release=self.butt_pressed))
return self.layout
def butt_pressed(self, button):
button.background_normal = ''
button.background_color = (1,0,0,1)
Th butt_pressed() method changes the background color of the pessed Button.
So i manage to get focus in the TextInput > tracknumb. at start of the app, but still when i confirm the input, finally i can do it with enter now too, but it looses the focus from textinput once i submit it.
Can you please advice what am I missing?
Whole Code here
import kivy
import kivy
import mysql.connector
from datetime import datetime
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.image import Image
from kivy.core.audio import SoundLoader
from kivy.core.window import Window
from kivy.clock import Clock
Window.size = (480, 800)
class MyGrid(GridLayout):
def __init__(self, **kwargs):
super(MyGrid, self).__init__(**kwargs)
self.cols = 1 # Set columns for main layout
self.inside = GridLayout(cols=2, row_force_default=True,
row_default_height=50, padding=20,
spacing=10) # Create a new grid layout
self.add_widget(Label(text="Tracking Number \n Checker", halign="center", font_size=40)) # Top Label
self.inside.add_widget(Label(text="Work Number:", halign="center", font_size=20)) # Add a label widget
self.worknumb = TextInput(text_validate_unfocus=True, multiline=False, font_size=20, halign="center")
self.inside.add_widget(self.worknumb)
self.inside.add_widget(Label(text="Tracking \nNO. Scan:", halign="center", font_size=20))
self.tracknumb = TextInput(multiline=False, font_size=15, halign="center") # Create a Text input box stored in the name variable
self.inside.add_widget(self.tracknumb) # Add the text input widget to the GUI
self.add_widget(self.inside) # Add the interior layout to the main
self.submit = Button(text="Submit", font_size=40, size_hint =(.5, .5)) # Submit button
self.add_widget(self.submit)
self.submit.bind(on_press=self.send_tracknumb)
self.resultbox = Image(source="status.png") #image box on bottom
self.add_widget(self.resultbox)
Window.bind(on_key_down=self.pressed)
Clock.schedule_once(self.focus_tracknumb, 1)
def pressed(self, instance, keyboard, keycode, text, modifiers):
if keycode == 40 or keycode == 13:
self.send_tracknumb(None)
def focus_tracknumb(self, _):
self.tracknumb.focus = True
def send_tracknumb(self, _):
tracknumb = self.tracknumb.text
worknumb = self.worknumb.text
errorsound = SoundLoader.load("incorrect.mp3") # add sound to the scanning
correctsound = SoundLoader.load("correct.ogg")
self.tracknumb.text = "" # Reset text to blank in each text input
I think you can change focus back to the TextInput in the pressed() method:
def pressed(self, instance):
tracknumb = self.tracknumb.text
worknumb = self.worknumb.text
errorsound = SoundLoader.load("incorrect.mp3") #add sound to the scanning
correctsound = SoundLoader.load("correct.ogg")
self.tracknumb.text = "" # Reset text to blank in each text input
self.tracknumb.focus = True # Change focus back to tracknumb
Och dong, I missed it :D it was so simple, I had to put the function to that part
def send_tracknumb(self, _):
I missed that one in all the text :{
Clock.schedule_once(self.focus_tracknumb, 0.1)
This is what it looks like when i run it, which is what i want except the flip button does nothingI have tried many fixes for other people but none worked so I am uploading my work in hopes that someone can help me. If you can please comment but you will likely have to put things in the simplest way possible as I don't have a lot of knowledge.
import kivy
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.button import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
class Shark(App):
def build(self):
self.max_food = 50
self.food = self.max_food
self.respect = 0
self.layout = BoxLayout(orientation="vertical")
area1 = BoxLayout(orientation="horizontal")
area2 = BoxLayout(orientation="horizontal")
area3 = BoxLayout(orientation="horizontal")
self.layout.add_widget(area1)
self.layout.add_widget(area2)
self.layout.add_widget(area3)
self.lbl1 = Label(text="{}/{} Food".format(self.food, self.max_food))
self.lbl2 = Label(text="{} Respect".format(self.respect))
area1.add_widget(self.lbl1)
area1.add_widget(self.lbl2)
btn1 = Button(text="Area 1")
btn2 = Button(text="Area 2")
area2.add_widget(btn1)
area2.add_widget(btn2)
btn3 = Button(text="Eat")
btn4 = Button(text="Flip")
btn4.bind(on_press=self.flip)
area3.add_widget(btn3)
area3.add_widget(btn4)
return self.layout
def eat(self):
pass
def flip(self, obj):
self.food -= 10
self.respect += 10
self.lbl1.text="{}/{} Food".format(self.food, self.max_food)
self.lbl2.text="{} Respect".format(self.respect)
Shark().run()
Change:
btn4.bind(on_push=self.flip)
To:
btn4.bind(on_press=self.flip)
I don't think on_push is a valid action.
I want to place image on button. Button's size depends on size of screen. I want to select ideal image's size according to button's size. Buttons are defined in class ButtonTools. With my knowledges I cann obtain size only in fuction of class ButtonTools. How do I obtain size of screen?
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.image import Image
class Paint(Widget):
pass
class ButtonTools(BoxLayout):
def __init__(self, **kwargs):
super(ButtonTools, self).__init__(**kwargs)
self.size_hint = (1, None)
self.height = 50
but = Button(on_press = self.DrawAbscissa)
but.background_normal = 'abscissa.png'
self.add_widget(but)
but = Button( on_press = self.DrawCurve)
but.background_normal ='curve.png'
self.add_widget(but)
def DrawAbscissa(self, obj):
size = self.parent.size
p=1
pass
def DrawCurve(self, obj):
pass
class WorkShop(BoxLayout):
def __init__(self, **kwargs):
super(WorkShop, self).__init__(**kwargs)
self.orientation = "vertical"
self.paint = Paint()
self.tools = ButtonTools()
self.add_widget(self.paint)
self.add_widget(self.tools)
class MyPaintApp(App):
def build(self):
return WorkShop()
if __name__ == '__main__':
MyPaintApp().run()
You can obtain the screen size using the following:
from kivy.core.window import Window
...
print("Window.size={}".format(Window.size))
print("Window.height={}".format(Window.height))
print("Window.width={}".format(Window.width))