Kivy按钮不可按

时间:2017-05-29 21:06:59

标签: python kivy

我根据文件夹中有多少声音文件动态创建按钮,但我遇到了无法按下任何按钮的问题。我尝试查找教程或类似的问题,但似乎我所拥有的应该是正确的,但是当我运行它时,我得到一个带按钮的窗口,但按下时按钮什么都不做。

import os, glob

from os.path import isfile, join
from os import listdir
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.config import Config
from kivy.app import App

Config.set('graphics', 'borderless', False)
Config.set('graphics', 'width', '500')
Config.set('graphics', 'height', '300')

class Soundboard(GridLayout):
def soundSearch(self):
    os.chdir("./sound")
    self.sounds = []
    for Wav in glob.glob("*.wav"):
        self.sounds.append(Wav)
    for Flac in glob.glob("*.flac"):
        self.sounds.append(Flac)
    for mp3 in glob.glob("*.mp3"):
        self.sounds.append(mp3)

def __init__(self,**kwargs):
    super(Soundboard, self).__init__(**kwargs)
    self.soundSearch()
    self.cols = 3
    for sound in self.sounds:
        self.button = Button(text=os.path.splitext(sound)[0])
        self.button.bind(on_press=lambda x:self.clk())
        self.add_widget(self.button)
    self.row_force_default = True
    self.row_default_height = 40
    self.padding = [50, 10]
    self.spacing = 5

def clk(self, *args):
    print('The button is pushed')
class MyApp(App):
    def build(self):
        return Soundboard()

if __name__ == '__main__':
    MyApp().run()

1 个答案:

答案 0 :(得分:0)

在您提供的代码中,缩进存在问题。除此之外,代码对我来说很好:

import glob
import os

from kivy.app import App
from kivy.config import Config
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout

Config.set('graphics', 'borderless', False)
Config.set('graphics', 'width', '500')
Config.set('graphics', 'height', '300')

class Soundboard(GridLayout):
    def soundSearch(self):
        self.sounds = []
        os.chdir("./sound")
        for Wav in glob.glob("*.wav"):
            self.sounds.append(Wav)
        for Flac in glob.glob("*.flac"):
            self.sounds.append(Flac)
        for mp3 in glob.glob("*.mp3"):
            self.sounds.append(mp3)

    def __init__(self,**kwargs):
        super(Soundboard, self).__init__(**kwargs)
        self.soundSearch()
        self.cols = 3
        for sound in self.sounds:
            self.button = Button(text=os.path.splitext(sound)[0])
            self.button.bind(on_press=lambda x: self.clk())
            self.add_widget(self.button)
        self.row_force_default = True
        self.row_default_height = 40
        self.padding = [50, 10]
        self.spacing = 5

    def clk(self, *args):
        print('The button is pushed')

class MyApp(App):
    def build(self):
        return Soundboard()

if __name__ == '__main__':
    MyApp().run()

Works as expected