python - 修改GridBagSizer时Wxpython奇怪的显示错误
问题描述
在下面的程序中,我运行了一种俄罗斯方块。我正在使用 WxPython 来显示它。块用命令移动,指示字母、数字和 < 或 >。例如:A7>。这意味着位置 A7 的块将沿箭头指示的方向移动。您将它添加到“Jugada:”TextCtrl 中,它会在引入时立即执行。当我用纯 python 编写“移动”部分时,它运行良好。但是显示功能是个问题。我第一次使用它时效果很好:
当我更改窗口大小时,一切都恢复正常,但有些数字以我不理解的方式显示:
这是整个代码,但是使用 wxpython 的程序部分是来自类 MenuFrame(wx.Frame) 的部分。这些块是带有信息 [x_position,length,color,y_position] 的列表。
import wx
import itertools
alto=12
def superponen(primero,otro):
if (otro[0] <= primero[0] < otro[0] + otro[1]):
return True
elif (otro[0] <= primero[0] + primero[1] - 1 < otro[0] + otro[1]):
return True
elif (primero[0] <= otro[0] < primero[0] + primero[1]):
return True
elif (primero[0] <= otro[0] + otro[1] - 1 < primero[0] + primero[1]):
return True
else:
return False
def bajar(bloque):
sobre_nada=True
if bloque[3] == 12:
sobre_nada = False
for bloque_que_probar in bloques:
if bloque_que_probar[3] == bloque[3] + 1:
if superponen(bloque, bloque_que_probar) == True:
sobre_nada = False
while sobre_nada==True:
bloque[3]+=1
if bloque[3] == 12:
sobre_nada=False
for bloque_que_probar in bloques:
if bloque_que_probar[3] == bloque[3] + 1:
if superponen(bloque, bloque_que_probar) == True:
sobre_nada=False
def ordenar_alturas(bloque):
return bloque[3]
def bloques_bajados():
global bloques
for elemento in sorted(bloques,key=ordenar_alturas, reverse=True):
bajar(elemento)
def entrada_a_bloque(codigo):
resultado=[]
leng=0
x=0
#AAabb b a
for i in range(len(codigo)):
leng += 1
if i+1!=len(codigo):
if codigo[i]==" ":
x+=1
leng=0
continue
if codigo[i]!=codigo[i+1]:
if ord(codigo[i])==65 or ord(codigo[i])==97:
resultado.append([x,leng,"#",1])
elif ord(codigo[i])==66 or ord(codigo[i])==98:
resultado.append([x,leng,"$",1])
else:
resultado.append([x, leng, "%", 1])
x+=leng
leng=0
else:
if codigo[i]==" ":
x+=1
leng=0
continue
if ord(codigo[i]) == 65 or ord(codigo[i]) == 97:
resultado.append([x, leng, "#", 1])
elif ord(codigo[i]) == 66 or ord(codigo[i]) == 98:
resultado.append([x, leng, "$", 1])
else:
resultado.append([x, leng, "%", 1])
return resultado
def bloque_puede_mover(jugada, bloque_movido):
y = "ABCDEFGHIJKL".index(jugada[0]) + 1
sentido=jugada[2]
en_misma_fila = []
for bloque in bloques:
if bloque[3]==y and bloque!=bloque_movido:
en_misma_fila.append(bloque)
if (bloque_movido[0]==0 and sentido=="<") or (bloque_movido[0]+bloque_movido[1]==10 and sentido==">"):
return False
for bloc in en_misma_fila:
if sentido=="<":
if bloc[0]+bloc[1]-1 == bloque_movido[0]-1:
return False
else:
if bloc[0]==bloque_movido[0]+bloque_movido[1]:
return False
return True
def sintaxis_correcta(decision):
if decision == "---":
return True
if len(decision) < 3 or len(decision)>3:
return False
if decision[0] not in "ABCDEFGHIJKL":
return False
if decision[1] not in map(str,range(10)):
return False
direccion = decision[2]
if direccion != "<" and direccion != ">":
return False
return True
def bloque_seleccionado(decision):
y = "ABCDEFGHIJKL".index(decision[0]) + 1
x = int(decision[1])
for bloque in bloques:
if bloque[3]==y and bloque[0] <=x < bloque[0] + bloque[1]:
return bloque
return False
def correcto(jugada):
if sintaxis_correcta(jugada) == False:
print("Error de sintaxis en jugada")
return False
bloque_mover=bloque_seleccionado(jugada)
if bloque_mover == False:
print("No hay ningún bloque en esa celda")
return False
if bloque_puede_mover(jugada, bloque_mover) == False:
print("El bloque no puede moverse en esa dirección")
return False
return bloque_mover
def jugar(block,jugada):
while bloque_puede_mover(jugada, block):
if jugada[2]=="<":
block[0]-=1
else:
block[0]+=1
def eliminar_lineas():
global bloques,puntuacion
se_ha_roto=False
for y in range(12):
linea=[]
for bloc in bloques:
if bloc[3]==y+1:
linea.append(bloc)
suma_longitudes = 0
for bloque_analizado in linea:
suma_longitudes += bloque_analizado[1]
if suma_longitudes == 10:
color = linea[0][2]
mismo_color = True
for bloque in linea:
if bloque[2] != color:
mismo_color = False
if mismo_color == True:
for bloque in bloques:
puntuacion += bloque[1]
bloques = []
else:
puntuacion += 10
for bloque in linea:
bloques.remove(bloque)
se_ha_roto = True
return se_ha_roto
#with open(input("Fichero de filas iniciales: "),"r") as archivo:
with open("D:/codigos.txt", "r") as archivo:
data=archivo.read()
archivo=data.split("\n")
bloques=[]
puntuacion=0
altura = 12
i=1
class MenuFrame(wx.Frame):
def __init__(self, *args, **kwds):
global bloques
# begin wxGlade: CalculatorFrame.__init__
# kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.SetSize((400, 300))
self.SetTitle("Deslizador")
self.Center()
self.half_sizer = wx.SplitterWindow(self, wx.ID_ANY)
self.settings = wx.Panel(self.half_sizer)
self.grid_side = wx.Panel(self.half_sizer)
# self.grid_side.SetBackgroundColour("red")
self.half_sizer.SetMinimumPaneSize(130)
# self.half_sizer.SetSashPosition(100)
self.half_sizer.SplitVertically(self.settings, self.grid_side)
self.options_separator = wx.BoxSizer(wx.VERTICAL)
self.fichero_separator = wx.BoxSizer(wx.HORIZONTAL)
self.label_fichero = wx.StaticText(self.settings, wx.ID_ANY, "Fichero: ")
self.fichero_separator.Add(self.label_fichero, 0)
self.control_fichero = wx.TextCtrl(self.settings, wx.ID_ANY)
self.fichero_separator.Add(self.control_fichero, 1, wx.EXPAND)
self.options_separator.Add(self.fichero_separator, 0, wx.EXPAND)
self.abr_fich = wx.Button(self.settings, wx.ID_ANY, "Abrir fichero")
self.options_separator.Add(self.abr_fich, 0, wx.EXPAND)
self.nuev_part = wx.Button(self.settings, wx.ID_ANY, "Nueva partida")
self.options_separator.Add(self.nuev_part, 0, wx.EXPAND)
self.sep_n_filas = wx.BoxSizer(wx.HORIZONTAL)
self.label_n_filas = wx.StaticText(self.settings, wx.ID_ANY, "N° Filas:")
self.sep_n_filas.Add(self.label_n_filas, 0, wx.ALIGN_CENTER_VERTICAL)
self.spin_n_filas = wx.SpinCtrl(self.settings, wx.ID_ANY, min=3, max=100, initial=12)
self.sep_n_filas.Add(self.spin_n_filas, 1, wx.EXPAND)
self.options_separator.Add(self.sep_n_filas, 0, wx.EXPAND)
self.sep_jugadas = wx.BoxSizer(wx.HORIZONTAL)
self.label_jugada = wx.StaticText(self.settings, wx.ID_ANY, "Jugada: ")
self.sep_jugadas.Add(self.label_jugada, 0, wx.ALIGN_CENTER_VERTICAL)
self.control_jugada = wx.TextCtrl(self.settings, wx.ID_ANY)
self.control_jugada.Bind(wx.EVT_TEXT,self.game)
self.sep_jugadas.Add(self.control_jugada, 1, wx.EXPAND)
self.options_separator.Add(self.sep_jugadas, 0, wx.EXPAND)
self.label_lista = wx.StaticText(self.settings, wx.ID_ANY, "Lista de jugadas:")
self.options_separator.Add(self.label_lista, 0)
self.lista = wx.ListBox(self.settings)
self.options_separator.Add(self.lista, 10, wx.EXPAND)
font = wx.Font(20, family=wx.FONTFAMILY_MODERN, style=0, weight=90, underline=False, faceName="",
encoding=wx.FONTENCODING_DEFAULT)
self.label_puntos = wx.StaticText(self.settings, wx.ID_ANY, "PTOS: 0")
self.label_puntos.SetFont(font)
self.options_separator.Add(self.label_puntos, 0, wx.CENTER)
self.settings.SetSizer(self.options_separator)
self.tabla = wx.GridBagSizer(5, 5)
nuevos = entrada_a_bloque(archivo[0])
for nuevo_bloque in nuevos:
#for nuevo_bloque in [[1,3,"A",12]]:
bloques.append(nuevo_bloque)
self.draw_table(bloques, self)
self.grid_side.SetSizer(self.tabla)
self.Layout()
self.Show()
def draw_table(self, blocks,parent):
global altura
parent.tabla.Clear(True)
#parent.tabla = wx.GridBagSizer(5, 5)
for a in range(altura):
text_add = wx.StaticText(parent.grid_side, wx.ID_ANY, "ABCDEFGHIJKLMOPQRSTUVWXYZ"[a])
parent.tabla.Add(text_add, wx.GBPosition(a, 0), wx.GBSpan(1, 1), flag=wx.EXPAND)
try:
parent.tabla.AddGrowableRow(a)
except wx._core.wxAssertionError:
pass
for b in range(1,11):
text_add = wx.StaticText(parent.grid_side, wx.ID_ANY, str(b))
parent.tabla.Add(text_add, wx.GBPosition(12, b), wx.GBSpan(1, 1), flag=wx.ALIGN_CENTER_VERTICAL)
try:
parent.tabla.AddGrowableCol(b)
except wx._core.wxAssertionError:
pass
for c in blocks:
block = wx.Panel(self.grid_side,style=wx.BORDER_SIMPLE)
if c[2]=="#":
block.SetBackgroundColour("green")
elif c[2]=="$":
block.SetBackgroundColour("blue")
else:
block.SetBackgroundColour("red")
parent.tabla.Add(block, wx.GBPosition(c[3]-1, c[0]+1), wx.GBSpan(1, c[1]), flag=wx.EXPAND)
parent.grid_side.SetSizer(parent.tabla)
def game(self,evt):
global altura, bloques, puntuacion, i, archivo,frame
mov=frame.control_jugada.GetValue()
if sintaxis_correcta(mov) and correcto(mov):
parent=frame
bloque=correcto(mov)
jugar(bloque,mov)
#parent.draw_table(bloques,parent)
caida = True
while caida:
bloques_bajados()
#parent.draw_table(bloques,parent)
caida = eliminar_lineas()
#parent.draw_table(bloques,parent)
for bloque in bloques:
if bloque[3] == 1:
print("FIN DE LA PARTIDA")
exit()
nuevos = entrada_a_bloque(archivo[i])
for nuevo_bloque in nuevos:
bloques.append(nuevo_bloque)
parent.draw_table(bloques, parent)
i+=1
if __name__ == "__main__":
global frame
app = wx.App()
frame=MenuFrame(None, wx.ID_ANY, "")
app.MainLoop()
这里有 D:/codigos.txt 文件中的文本:
ABCcBAaB c
ABbBb BAa
AB a A B
A Aa B A
BB Aaaa
A B bBAABB
AAa AB AAA
BBBA B
BbBBBABb b
a aaa A
Bb BbAAAaa
B AAABAB
ABb b ABB
AABbb a A
BBb AAA AB
AaaaBbb aa
BAaABBBB A
AB AAaaaBb
BAAB B bA
BbBA AaAAa
AAA bbAAAA
B bBAAa B
AaaA a b
我做了一个测试:打开窗口时我没有显示积木。这有相同的错误,排除了清除图表时出错的可能性。
解决方案
推荐阅读
- c++ - 如何在 C++ 向量(特征)中获得最大的 n 值?
- python-3.x - 从包含子字符串的列表中删除元素,例如“第 1 页,共 67 页”或“第 2 页,共 67 页”
- c - 使用嵌套循环和 If/Else 语句展开循环 10 x 10 展开
- stm32 - 如何使用 ATLINK/V2 UART 通信烧写程序
- excel - 通过 VBA 在工作表上插入的 ActiveX 标签在右侧和底部显示白色边框
- r - 检查正态分布错误
- python - 用于估算 NaN 值并给出值错误的简单 Imputer
- mysql - 在 desc 订单限制中显示客户时出错 5
- openlayers - 根据 OpenLayers 的业务趋势 - OpenLayers 支持的功能将在多大程度上保持免费?
- laravel - Laravel 迁移 - 将列放在另一列之前