python - kivy按钮文本=""逻辑错误

标签 python python-3.x kivy

我是python和kivy的新手,我试图通过制作一个小型扫雷游戏来学习python,但是,我觉得下面代码中的逻辑是正确的,但不知何故似乎不起作用:完整文件如下:

from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
import random

class spot(Button):
    '''
    classdocs
    '''
    def __init__(self, **kwargs):
        '''
        Constructor
        '''
        super(spot,self).__init__(**kwargs)
        self.ismine=False
        self.text="X"
        if 'id' in kwargs:
            self.id=kwargs['id']
        #else:
        #    self.text="X"    


class minesholder(GridLayout):

    def __init__(self,**kwargs):
        super(minesholder,self).__init__(**kwargs)

class game(BoxLayout):
    spots={}
    mines=[]

    def __init__(self,**kwargs):
        super(game,self).__init__(**kwargs)
        self.m=minesholder(rows=5, cols=5)
        self.add_widget(self.m)
        self.attachtogrid()

    def attachtogrid(self):
        self.m.clear_widgets()
        self.spots.clear()
        for r in range(0,5):
            for c in range(0,5):
                idd=str(r)+","+str(c)
                self.spots[idd]=idd
                s = spot(id=idd)
                self.m.add_widget(s)
                s.bind(on_press=self.spottouched)
                print(idd)
        self.createmines()

    def createmines(self):
        self.mines.clear()
        count=0
        while (count <= 10):
            c=str(random.randint(0,4))+','+str(random.randint(0,4))
            print(c)
            if self.mines.count(c)==0:
                self.mines.append(c)
                count+=1        

    def spottouched(self,spotted):        
        #if self.mines.count(str(spotted.id))==1:
        #    spotted.text="BOMB"
        #else: spotted.text=""
        for k in self.mines:
            if k==spotted.id: spotted.text="BOMB"
            else:
                spotted.text=""                

问题是最后 4 行,当我删除“spotted.text=""”时,代码工作完美,但是当我保留 text=""时,代码不再工作,尽管有11 个炸弹中只有 1 个被检测到,如果没有 text="",所有炸弹都会被正确检测到(text="BOMB"有效)。

最佳答案

每次调用 spottouched() 时,您都会循环遍历每个地雷并相应地设置文本。但是,假设您有两个炸弹 - 我们将这些炸弹称为['bomb-a', 'bomb-b']

现在您触摸 ID 为'bomb-a' 的按钮。 spottouched() 循环遍历地雷。列表中的第一个地雷是 'bomb-a' - 因此它将文本设置为 "BOMB"。然后它循环 - 列表中的第二个地雷是 'bomb-b',因此文本设置回 ""。因此,唯一会显示“BOMB”文本的地雷是列表中的最后一个地雷。

尝试这样的事情:

def spottouched(self, spotted):
    spotted.text = "BOMB" if spotted.id in self.mines else ""

关于python - kivy按钮文本=""逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24460217/

相关文章:

限制可能值的 Python 类型提示友好类型

android - Windows 上的 Python/Kivy 应用程序到 apk - 安装虚拟机后该怎么办?

python - 无法从使用 PyInstaller 构建的 Kivy 应用程序中获取 lexers.PythonLexer()

Python Import No Module Named 错误

Python 的 'with' 语句与 'with .. as'

python - 如何将 lineedit 中的内容插入到 MySQL 中?

python - 尝试检索搁置类时的 KeyError 和 AtributeError - Python 3.6

python - 在这个信号量示例中,是否有必要为 refill() 和 buy() 锁定?

python - 加快动画 gif kivy 的加载

python - pandas.Period 可以代表任意时间跨度吗?